我正在使用角度5,并且正在努力使用可观察性从其余端点将数据显示在模板上。
我的组件如下
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方法打印到控制台,但模板中将不会输出任何内容
我正在尝试使用此模板-https://github.com/maliksahil/SPFxAngularCLI
为共享点框架创建一个有角度的应用程序有人能看到我在做什么吗?
答案 0 :(得分:1)
使用ChangeDetectorRef
constructor(private newsService: NewsService,private cdr:ChangeDetectorRef) {
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.cdr.detectChanges()
this.test = 'Hello';
console.log('3 Component newsItems:', this.newsItems);
console.log('4 Component test:', this.test);
}
);
}
}