Rahul Devgan Rahul Devgan - 10 days ago 6
AngularJS Question

How to change VIEW when data arrives in angular 2?

I am calling a service from my component that returns me json data, Here is my code

import {Component,Input,Output} from 'angular2/core';
import {PostService} from './post.service';
import {OnInit} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'postC',
template: `
<div>
{{isLoading}}
</div>
`,
providers: [PostService]
})
export class PostComponent implements OnInit {
@Input() isLoading = true;
@Input() y :any;
@Input() eventsArray;

constructor(private _postService: PostService){}
ngOnInit(){
this._postService.getPost("California");
this.y = this._postService.notifyParent
.subscribe(item => {
this.eventsArray = item.events.event[0];
this.isLoading = false;
console.log(this.isLoading);
})
}
}


here notifyParent = new EventEmitter() in my services component. Which emits event when it receives data.

The problems are:

1) isLoading is always showing true. Even after the observables updates its value to false.

2) I am not able to display the JSON data returned. Because the view already renders before I receive data.

There is a reason I am using event emitter and not http request. I am building this application for my school project and it has to run on localhost, which isn't able to make http reqests due to CORS issue.

Answer

The problem is that your service for some reason is breaking the angular zone, so when you subscribe the change detection doesn't run.

We can force the change detection manually. Import ChangeDetectorRef and run detectChanges() in your subscribe.

import {Component,Input,Output,ChangeDetectorRef} from 'angular2/core';
import {PostService} from './post.service';
import {OnInit} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'postC',
template: `
 <div>
{{isLoading}}
</div>
`,
providers: [PostService]
})
export class PostComponent implements OnInit {
public isLoading = true;
public y :any;
public eventsArray;

constructor(private _postService: PostService, private cdRef: ChangeDetectorRef){}
ngOnInit(){
    this._postService.getPost("California");
    this.y = this._postService.notifyParent
    .subscribe(item => {
        this.eventsArray = item.events.event[0];
        this.isLoading = false;
        console.log(this.isLoading);
        this.cdRef.detectChanges();
    }) 
  }
}
Comments