【问题标题】:angular 5 consoling http toPromise() request returns undefined角度 5 安慰 http toPromise() 请求返回未定义
【发布时间】:2018-05-04 02:39:24
【问题描述】:

我正在使用 Http 导入以 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 的内容,检查也没有显示任何内容......我可能出了什么问题?

【问题讨论】:

  • 那是因为你已经在消费fetchCategories() of ietm-category.ts中的Promise

标签: javascript angular angular5 angular-http


【解决方案1】:

这是因为您在返回响应之前记录了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();
}

无需在服务中消费promise

【讨论】:

  • 和以前一样,仍然未定义@Vandesh
  • 你能在成功承诺里面console.log(response)分享结果吗?
  • 我该怎么做?当我 console.log 进入 promise 时显示红色错误
  • 您需要删除您在代码中添加的第一个 console.log()。根据更新的答案进行更改,它应该可以工作
  • 如前所述完成了编辑,但现在在此处抛出错误错误this.categorys = response.results 错误“响应”类型上不存在属性“结果”
【解决方案2】:

将 observable 更改为 promise 没有任何好处

让服务返回一个 observable:

//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。因此,在值已发出(在可观察的情况下)或已解决(承诺)之前,您只有正确的结果。

【讨论】:

  • 错误 Property 'then' does not exist on type 'Observables&lt;any&gt;' @ChristianBenseler
  • 我犯了一个错误,不得不将'then'改为'subscribe'
  • 是的,感谢您的更正,没有更多错误,但在控制台中仍未定义,我认为没有任何内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 2019-10-09
  • 2019-06-17
  • 1970-01-01
  • 2018-08-09
相关资源
最近更新 更多