I'm stuck weeks about how to notify Component 2 from Component 1 that the data has been updated and you should bind it without refresh. I will inform you my code maybe someone can know what is the wrong with my concept.
I have two components (news-feed) and (post).
news-feed.component.ts:
EDIT
This is get sharedData
get sharedData() //<--a getter
{
return this._newElement.sharedData;
}
This is ngOnInit()
ngOnInit() {
this._newElement.data.subscribe((param: any) => { //<--subscribe to an observable
this.data=param;
});
In my post component onsuccess I used this._newElement.change(this.result.data);
And inside newsFeed() this._newElement.sharedData=this.result.data.posts;
and in my html I replaced data
with sharedData
.
End of EDIT
newsFeed() {
this._newsFeedService.newsFeedService(this.user)
.subscribe(
response => {
this.result = response;
if (this.result.code == -502) {
// error
}
} else if (this.result.code == 1) {
this.data = [] = this.data || [];
this.result.data.posts.forEach(item => {
this.data.push(item);
});
}
else {
this.alert = this._appService.newAlert('danger', this.result.msg);
}
},
error => console.log(error)
);
}
news-feed.service.ts:
@Injectable()
export class NewsFeedService {
private newsFeedAPI = AppGlobals.API_URL + 'news_feed/news-feed.php';
constructor(private _appService: AppService) {
}
newsFeedService(value: Object) {
return this._appService.LoadAPI(value, this.newsFeedAPI);
}
}
news-feed.ts:
export class NewsFeed {
user_id: string;
session_key: string;
page: number;
postText: string;
postID: any;
constructor() {
}
}
And this is my LoadAPI()
that I'm using above, it is in app.service.ts:
public LoadAPI(data: Object, API: string): Observable<any> {
const headers = new Headers();
headers.append('Content-Type',
'application/x-www-form-urlencoded;charset=utf-8');
return this._http.post(API, data, {
headers: headers
}).map(res => res.json());
}
Now in my html I'm displaying the data as usual:
<div *ngFor="let item of sharedData" id="{{item.post_id}}" class="post_{{item.post_id}}">
<article class="hentry post card_{{item.post_id}}">
//data
</article>
</div>
The big question is:
In my post.component.ts
I have insertPost()
function and onSuccess it returns new data that the news-feed.component
should detect it. What is the main idea?