简体   繁体   English

angular 5安慰http toPromise()请求返回未定义

[英]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. 我正在使用Http import在Angular 5中调用api端点来填充选择下拉列表,但是当我将其登录到控制台时该下拉列表却没有定义,并且下拉列表中没有填充任何数据...这意味着是项目类别。

item-category.ts 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 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 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? 这就是我所拥有的,但是不确定的是我在控制台中得到的,并且下拉菜单中的api没有任何内容,检查也未显示任何内容...我怎么可能出错了?

That's because you're logging this.categorys before the response is returned. 这是因为您在返回响应之前记录了this.categorys

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. 另外,您需要删除服务的fetchCategories()函数中的fetchCategories()和.catch()处理函数。 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. 请记住,所有http请求(例如this.http.get)都是异步的,返回的是observable或promise。 So you only have the proper result before it the value has been emitted (in the case of an observable) or resolved (promise). 因此,只有在值已发出(在可观察的情况下)或已解决(承诺)之前,您才具有正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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