angular 5 consoling http toPromise()请求返回undefined

时间:2018-05-03 17:41:21

标签: javascript angular angular5 angular-http

我在角度5中调用api端点,使用Http导入来填充选择下拉列表,但是当我将其记录到控制台并且下拉列表没有填充任何数据时我得到了未定义...它意味着是项目类别

项-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>

这就是我所拥有的,但未定义的是我在控制台中得到的内容,下拉列表中没有任何内容,检查也没有显示任何内容......我可能出错了什么?

2 个答案:

答案 0 :(得分:0)

那是因为您在返回响应之前记录this.categorys

尝试

    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
    }

此外,您需要删除服务的fetchCategories()函数中的.then()和.catch()处理程序。它应该只是 -

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

无需消耗服务中的承诺

答案 1 :(得分:0)

将observable更改为promise

没有任何好处

让服务返回一个可观察的:

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

并在您的组件中,将其作为可观察的

使用
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)

请记住,所有http请求(例如this.http.get)都是异步的,要么返回observable,要么返回promise。因此,只有在发出值(在可观察的情况下)或已解决(承诺)之前,您才能获得正确的结果。