Reputation: 4121
I am using angular 5 and I am struggling to get data to display on my template from a rest endpoint using observables.
My component is as follows
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);
}
);
}
}
My service is as follows
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'
});
}
}
The data is printing to the console in the ngOnInit method but nothing will output in the template
I am trying to create an angular application for the sharepoint framework using this template - https://github.com/maliksahil/SPFxAngularCLI
Can anyone see what I am doing wrong?
Upvotes: 0
Views: 1123
Reputation: 27303
Use 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);
}
);
}
}
Upvotes: 1