admin管理员组

文章数量:1426033

I am calling an api endpoint in angular 5 using Http import to populate a select dropdown but I am getting undefined when i log it to the console and the dropdown does not populate with any data...its meant to be item categorys.

item-category.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import {Router} from '@angular/router';
import { Globals } from '../shared/api';
import { of } from 'rxjs/observable/of';
import 'rxjs/add/operator/toPromise';
declare var $: any;

@Injectable()
export class ItemCategoryService{
    private categoryUrl = this.globals.CATEGORYS_URL;
    constructor(private http: Http, private globals: Globals,  private router:Router) { }

fetchCategories(){
    let v = this.page_header();
    return this.http.get(this.categoryURL, v)
        .toPromise()
        .then(response => response.json())
        .catch(this.handleError);
    };
}

itemCategoryponent.ts

fetchCategorys(){
    this.categorySrv.fetchCategories().then(response =>this.categorys = response.results  )
    .catch(error=> this.error = error )
    console.log(this.categorys);   // <== undefined
}

itemCategoryponent.html

<select class="form-control" [(ngModel)]="product.category"[formControl]="productForm.controls['productCategory']" require>
    <option *ngFor="let item of categorys" [value]="item.slug">{{item.name}}</option>
</select>

This is what I have but undefined is what i get in the console and the dropdown has nothing from the api, inspecting shows nothing also...what could I have gotten wrong?

I am calling an api endpoint in angular 5 using Http import to populate a select dropdown but I am getting undefined when i log it to the console and the dropdown does not populate with any data...its meant to be item categorys.

item-category.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import {Router} from '@angular/router';
import { Globals } from '../shared/api';
import { of } from 'rxjs/observable/of';
import 'rxjs/add/operator/toPromise';
declare var $: any;

@Injectable()
export class ItemCategoryService{
    private categoryUrl = this.globals.CATEGORYS_URL;
    constructor(private http: Http, private globals: Globals,  private router:Router) { }

fetchCategories(){
    let v = this.page_header();
    return this.http.get(this.categoryURL, v)
        .toPromise()
        .then(response => response.json())
        .catch(this.handleError);
    };
}

itemCategory.ponent.ts

fetchCategorys(){
    this.categorySrv.fetchCategories().then(response =>this.categorys = response.results  )
    .catch(error=> this.error = error )
    console.log(this.categorys);   // <== undefined
}

itemCategory.ponent.html

<select class="form-control" [(ngModel)]="product.category"[formControl]="productForm.controls['productCategory']" require>
    <option *ngFor="let item of categorys" [value]="item.slug">{{item.name}}</option>
</select>

This is what I have but undefined is what i get in the console and the dropdown has nothing from the api, inspecting shows nothing also...what could I have gotten wrong?

Share Improve this question asked May 3, 2018 at 17:41 CE0CE0 1913 gold badges7 silver badges18 bronze badges 1
  • That's because you are already consuming the Promise in fetchCategories() of ietm-category.ts – Ashish Ranjan Commented May 3, 2018 at 17:49
Add a ment  | 

2 Answers 2

Reset to default 1

That's because you're logging this.categorys before the response is returned.

try with

    fetchCategorys(){
        this.categorySrv.fetchCategories().then((response: any) => {  
               this.categorys = response.results; 
               console.log(this.categorys); // Log here instead of outside the promise  
        })
        .catch(error=> this.error = error )
        // Remove this console.log()
        console.log(this.categorys);   // <== It is correct to be undefined here because it is not in the success promise
    }

Also, you need to remove the .then() and .catch() handler inside the service's fetchCategories() function. It should just be -

fetchCategories(){
    let v = this.page_header();
    return this.http.get(this.categoryURL, v)
        .map(response => response.json())
        .toPromise();
}

No need to consume the promise in the service

There is no benefit in changing your observable to a promise

Keep the service returning an observable:

//service
fetchCategories(){
    let v = this.page_header();
    return this.http.get(this.categoryURL, v)
    .map(response => response.json())
}

and in your ponent, consume it as an observable

this.categorySrv.fetchCategories().subscribe( (response: any) => {  
 this.categorys = response.results; 
  console.log(this.categorys); // Log here instead of outside the observable  
}, error=> this.error = error)

remember that all http requests (such as this.http.get) are asynchronous, either returning observable or promise. So you only have the proper result before it the value has been emitted (in the case of an observable) or resolved (promise).

本文标签: javascriptangular 5 consoling http toPromise() request returns undefinedStack Overflow