I am completely new to Angular.
Currently, I am retrieving the list of posts from the server using the code snippet below:
loadPosts():boolean{
if (!LoginService.authenticated){
console.log('not auth');
return false;
}
// fetching posts.
console.log('load');
PostService.fetchPosts(
(response: Response) => {
HomeComponent.allPosts = response;
console.log("POSTS");
console.log(HomeComponent.allPosts);
});
The PostService.fetchPosts
function provides a response that is then stored in the allPosts
variable.
However, when it comes to displaying these posts in the view:
<div *ngIf="!authenticated(); else elseBlock">
Please log in first.
</div>
<ng-template #elseBlock>
<div *ngFor="let post of allPosts">
{{ post.heading }}
</div>
</ng-template>
I noticed that my list of posts is not being refreshed or updated as expected.
In the home.component.ts file:
export class HomeComponent implements OnInit {
static allPosts;
constructor(private ref: ChangeDetectorRef, private loginService: LoginService, private http: HttpClient, private postService: PostService) {
this.loginService.authenticate(undefined, undefined, undefined);
// setInterval(() => { console.log('checking'); this.ref.detectChanges}, 500 );
}
ngOnInit() {
this.loginService.authenticate(undefined, this.loadPosts, undefined);
}
authenticated(){
return LoginService.authenticated;
}
add(){
HomeComponent.allPosts = [{heading:'okay'}];
}
loadPosts():boolean{
if (!LoginService.authenticated){
console.log('not auth');
return false;
}
// fetching posts.
console.log('load');
PostService.fetchPosts(
(response: Response) => {
HomeComponent.allPosts = response.json();
console.log("POSTS");
console.log(HomeComponent.allPosts);
});
}
}
Regarding the post.service.ts file:
export class PostService {
static getPostUrl = 'http://localhost:8009/user/getposts';
static http;
constructor(private http: HttpClient) { PostService.http = http }
static fetchPosts(successCallback, errorCallback?){
this.http.get(this.getPostUrl, { withCredentials: true }).subscribe(
(response: Response) => {
successCallback(response);
},
(error) => {
console.log(error);
errorCallback? errorCallback(error) : {};
}
);
}
}