簡體   English   中英

angular 5安慰http toPromise()請求返回未定義

[英]angular 5 consoling http toPromise() request returns undefined

我正在使用Http import在Angular 5中調用api端點來填充選擇下拉列表,但是當我將其登錄到控制台時該下拉列表卻沒有定義,並且下拉列表中沒有填充任何數據...這意味着是項目類別。

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>

這就是我所擁有的,但是不確定的是我在控制台中得到的,並且下拉菜單中的api沒有任何內容,檢查也未顯示任何內容...我怎么可能出錯了?

這是因為您在返回響應之前記錄了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()函數中的fetchCategories()和.catch()處理函數。 應該只是-

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

無需在服務中兌現承諾

將您的可觀察性變為承諾沒有任何好處

保持服務返回可見:

//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。 因此,只有在值已發出(在可觀察的情況下)或已解決(承諾)之前,您才具有正確的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM