简体   繁体   English

Angular2 http.get数据不会在html模板中呈现

[英]Angular2 http.get data will not render in html template

I'm new to Angular2 and I'm struggling with getting the data returned from an http.get() Observable to display in my html. 我是Angular2的新手,我正努力从http.get()返回可观察到的数据显示在html中。 I have narrowed down the problem to get() calls to one of my api's. 我已经缩小了对我的一个API的get()调用的范围。 If I use another api endpoint, the data displays without issue in the html. 如果我使用其他api端点,则数据显示不会出现在html中。 I know my api is retrieving the data because when I console.log() the data, the expected output is there. 我知道我的api正在检索数据,因为当我console.log()数据时,期望的输出就在那里。

Service 服务

//color.service.ts
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs/RX'
import { Http, Response, Headers, RequestOptions } from '@angular/http'

@Injectable()
export class ColorService {

   constructor(private http:Http){
   }

   getColors():Observable<IColor[]> {
      return this.http.get('/colors')
      .map((response: Response) => {
         return <IColor[]>response.json();
      })
   }
}

Component 零件

//color.component.ts
import { Component, OnInit } from '@angular/core';
import { ColorService } from './shared/color.service';
import { IColor } from './shared/outage.model';

@Component({
    template: `
        <h4>Colors[]</h4>
        <div *ngFor="let c of colors">{{ c.colorDesc }}</div>
    `
})
export class ColorComponent implements OnInit {
    colors: IColor[];

    constructor(private colorService:ColorService ) {}

    ngOnInit(){
        this.colorService.getColors().subscribe(data => {
            console.log(data);
            this.colors = data;
        })
    }
}

IColor is a simple interface: IColor是一个简单的界面:

export interface IColor {
   colorDesc: string;
}

The resulting html output is simply the <h4>Colors[]</h4> heading; 产生的html输出只是<h4>Colors[]</h4>标题; however, you can see in the console log that the call to http.get('/colors') was successful and the IColor[] object is populated. 但是,您可以在控制台日志中看到对http.get('/colors')的调用成功,并且已填充IColor[]对象。 An inspection of the DOM shows that there are empty <div> elements, created by the *ngFor . 对DOM的检查表明,存在由*ngFor创建的空<div>元素。

As mentioned above, an http.get() to another endpoint works as expected: the data is shown in the html. 如上所述,到另一个端点的http.get()可以按预期工作:数据显示在html中。 I am struggling to understand why data from another api will not show in the DOM. 我正在努力理解为什么来自另一个API的数据将不会显示在DOM中。 It does appear to take 1-2 seconds longer to retrieve, but my understanding of Observable subscriptions is that these are async operations; 检索似乎确实需要1-2秒以上的时间,但是我对Observable订阅的理解是,这些是异步操作。 when it completes, the html should render the data from the *ngFor . 完成后,html应从*ngFor呈现数据。

If the divs are rendering but no data is populated, then there is a mismatch between what you parse out of your response and what you are binding to the template. 如果div正在渲染,但没有填充数据,则从响应中解析出的内容与绑定到模板的内容之间将不匹配。 I'd hunt for typos, but anecdotally, I have a lot of issues using interfaces and the angular CLI. 我会寻找错别字,但有趣的是,使用接口和有角度的CLI会遇到很多问题。 I usually need to re compile everytime I edit an interface. 我通常在每次编辑界面时都需要重新编译。

I'd try getting rid of that explicit typing in your map function, it isn't needed, it's already inferred from the return type of the function and doesn't actually do anything helpful. 我会尝试摆脱map函数中的显式键入,这不是必需的,它已经从函数的返回类型中推断出来了,实际上并没有任何帮助。 I can't comment further without seeing your data returned. 如果看不到您的数据,我无法发表进一步评论。

Secondly, a better way to bind observables to templates is with the async pipe rather than subscribing in your component.ts, like so: 其次,将可观察对象绑定到模板的更好方法是使用异步管道,而不是订阅component.ts,如下所示:

colors$ : Observable<IColor[]>;

constructor(private colorService:ColorService ) {}

ngOnInit(){
    this.colors$ = this.colorService.getColors().do(e => console.log(e)); //do just for debugging
}

and template: 和模板:

<div *ngFor="let c of colors$ | async">{{ c.colorDesc }}</div>

The reasons for this are it is cleaner, more declarative, and most importantly the async pipe handles garbage collection for you. 这样做的原因是它更干净,更具声明性,并且最重要的是异步管道为您处理垃圾收集。

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

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