【发布时间】:2019-01-14 18:39:27
【问题描述】:
我正在使用 Angular 5,我正在努力使用 observables 从一个休息端点获取数据以显示在我的模板上。
我的组件如下
import { Component, OnInit, Input } from '@angular/core';
import { NewsService } from './news.service';
import { NewsItem } from './newsItem.model';
import { Observable } from 'rxjs';
@Component({
selector: 'app-news',
//templateUrl: './news.component.html',
template: `
<ul>
<li *ngFor="let newsItem of newsItems">{{newsItem}}</li>
</ul>
<h3 *ngIf="newsItems"> {{ newsItems }} </h3>
<h3 *ngIf="test"> test: {{ test | async}} </h3>`,
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
newsItems: NewsItem[];
test : string;
constructor(private newsService: NewsService) {
this.newsItems = [];
}
ngOnInit() {
this.newsService.getLatestNews().subscribe(
data => {
console.log('1 Component Data:', data);
data.forEach(function (newsItem) {
console.log('2 Component Data:', newsItem);
});
this.newsItems = data;
this.test = 'Hello';
console.log('3 Component newsItems:', this.newsItems);
console.log('4 Component test:', this.test);
}
);
}
}
我的服务如下
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpRequest } from '@angular/common/http';
import 'rxjs';
import { NewsItem } from './newsItem.model';
import { Observable } from 'rxjs';
@Injectable()
export class NewsService {
newsEndpoint:string = 'http://myendpoint.com/services/news';
constructor(private httpClient: HttpClient) { }
getLatestNews(): Observable<NewsItem[]>{
return this.httpClient.get<NewsItem[]>(this.newsEndpoint, {
observe: 'body',
responseType: 'json'
});
}
}
数据在 ngOnInit 方法中打印到控制台,但模板中不会输出任何内容
我正在尝试使用此模板为 sharepoint 框架创建一个 Angular 应用程序 - https://github.com/maliksahil/SPFxAngularCLI
谁能看出我做错了什么?
【问题讨论】:
-
应该工作@第一眼。你能创建 Stackblitz 吗? (只是模拟服务中返回的数据)
-
可能在运行时抛出了某种异常?
-
从Angular5(或4)开始也可以省略
observe: 'body', responseType: 'json' -
@Component 装饰器中没有“模板”属性?
-
去掉了 observe: 'body', responseType: 'json' 和它一样。
标签: angular angular5 observable