简体   繁体   中英

angular 5 consoling http toPromise() request returns undefined

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.component.ts

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

itemCategory.component.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?

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 component, 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM