在我的Angular2项目中,我正在显示一个用户列表,我有一个添加按钮,当我添加新用户而不刷新页面时,我想将新添加的用户显示给我当前显示的用户列表。我来了以下解决方案,但在我的subscriber.component.ts文件中我调用this.getSubscribers();函数两次,第一次给出空指针异常。可能是什么解决方案?除了我目前用于显示而没有刷新的内容之外,还有其他方法吗? 这是我的代码..
subscriber.component.html
<tr *ngFor="let subscriber of mf.data">
<td>{{subscriber.name}}</td>
<td>{{subscriber.email}}</td>
<td>{{subscriber.mdn}}</td>
<td class="text-center">
<md-icon (click)="goToSubscriberDetails(subscriber)" mdTooltip="View Details">
remove_red_eye
</md-icon>
<md-icon mdTooltip="Edit" (click)="openEditDialog(subscriber)">edit</md-icon>
<md-icon mdTooltip="Recharge" (click)="rechargeDialog(subscriber)">attach_money</md-icon>
</td>
</tr>
subscriber.component.ts
ngOnInit(): void {
this.currentPage = 1;
this.pageStart = 0;
this.subscriberService
.getSubscribers(0, 10, this.currentPage).subscribe(data => {
this.subscribers = data.data;
this.totalSubscriberLength = data.total;
});
this.sharedService.notifySubscriberObservable$.subscribe((res) => {
this.getSubscribers(); // null pointer exception
this.getSubscribers();
console.log("in Subscriber template refresh")
});
}
adddialog.component.ts
this.subscriberService.addSubscriber(data).subscribe(data => {
let responseJson=data.json();
if (responseJson.success)
{
this.toasterService.pop('success', 'SUCCESS', SUBSCRIBER_ADD_SUCCESS_MESSAGE);
this.sharedService.notifyOtherSubscriber();
}
else
this.toasterService.pop('error', 'FAILED',SUBSCRIBER_ADD_FAILURE_MESSAGE);
}
global.ts
private notify = new Subject<any>();
notifyObservable$ = this.notify.asObservable();
constructor(){}
public notifyOther()
{
this.notify.next();
}
private notifySubscriber = new Subject<any>();
notifySubscriberObservable$ = this.notifySubscriber.asObservable();
public notifyOtherSubscriber() {
this.notifySubscriber.next();
}