我有被分配的值的服務共享組件之間的變量如下,爲什麼我不能分配和使用組件內的值?
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AppMessageQueuService {
checkOutPageParams: Subject<Object>;
constructor() {
this.checkOutPageParams = new Subject<string>();
}
}
我使用這項服務於以下參數傳遞到另一組件時,
this.appMsgService.checkOutPageParams.next({
'userId': listItem.userInfo.userId,
'listingId': listItem.listingId,
'event': this.event
});
我可以看到到事件當我調試,這是我如何得到在第二個組件的值,
this.appMsgService.checkOutPageParams.asObservable()
.switchMap((params: Object) => {
let userId = params['userId'];
let listingId = params['listingId'];
this.event = params['event'];
return this.checkOutInforService.getCheckoutDetails(userId, listingId);
}).subscribe((checkoutDetail: CheckoutUserDetail) => {
this.checkoutInfoDetails = checkoutDetail;
});
console.log(this.event) //this returns undefined
我可以看到值分配給事件以及。但是當我在上面的行後面打印一個console.log(this.event)時,它說undefiend。
問題是什麼。我怎麼能值分配給事件和組件2
你就是不行。 Observable是異步的,因此console.log在分配this.event之前執行。在'subscribe'塊中移動語句。 – pixelbits
如何使用該值然後 – Sajeetharan
使用您的訂閱塊內的值。 – pixelbits