将订阅方法中的值分配给属性

时间:2016-04-04 08:58:49

标签: angular

首先,我希望您检查一下:

load(){
   return this._http.get(url)
        .map(res => {
            return res.json();
        })
        .map(data=>{
            //some code
            return {notifs,cpt};
         });
}

export class HomePage {

notificationsList: Array<Notification> = [];
nonLu: number;

constructor(
    private _userService: UserService,
    private _router: Router,
    public _notificationService: NotificationsService) {
    _notificationService.load()
        .subscribe(res => {
            this.nonLu = res.cpt;
            res.notifs.forEach((resObject) => {
                this.notificationsList.unshift(resObject);
            });
        });


}

}

正如您在notification.service.ts文件中看到的那样,我有加载方法来加载特定用户的通知(为了更准确,该方法还返回通知和未读通知的数量)。

由于load方法返回一个Observable,我必须在home.component.ts中使用subscribe方法。在订阅方法中,我想分配属性&#34; nonLu&#34;一定的值(在这种情况下是res.cpt)。但是当我在subscribe方法中键入console.log(nonLu)时遇到问题,我有预期的值。否则,我得到了未定义。

我该怎么做才能解决这个问题?

谢谢

更新

constructor( private _userService: UserService, private _router: Router, public _notificationService: NotificationsService) {
    _notificationService.load() 
    .subscribe(res => { 
        res.notifs.forEach((resObject) => {    
            this.notificationsList.unshift(resObject); 
        }); 
        this.nonLu = res.cpt; 
        console.log("Inside subscribe : " + this.nonLu); 
     }); 
     console.log("Outside subscribe : " + this.nonLu); 
}

2 个答案:

答案 0 :(得分:0)

Observables是异步的,这意味着传递给subscribe(...)的回调最终会被执行但不会立即执行。 JavaScript(或TypeScript)继续使用下一个代码行执行 subscribe()仅用于注册兴趣,以便在发出值时调用自己的代码。

constructor(
    private _userService: UserService,
    private _router: Router,
    public _notificationService: NotificationsService) {
    _notificationService.load()
        .subscribe(res => {
            this.nonLu = res.cpt;
            res.notifs.forEach((resObject) => {
                this.notificationsList.unshift(resObject);
        });
        /// code here is executed before the callback passed to subscribe
    });
}

答案 1 :(得分:0)

正如冈特所说的那样。但作为一种解决方法,您可以使用setInterval。虽然这不是最佳解决方案,但可以视为一种解决方法。

constructor( private _userService: UserService, private _router: Router, public _notificationService: NotificationsService) {
    _notificationService.load() 
    .subscribe(res => { 
        res.notifs.forEach((resObject) => {    
            this.notificationsList.unshift(resObject); 
        }); 
        this.nonLu = res.cpt; 
        console.log("Inside subscribe : " + this.nonLu); 
     }); 

     let i=setInterval(()=>{
         if(this.nonLu)
         {
             console.log(this.nonLu);
             clearInterval(i);
         }
     },1000)

}
相关问题