我試圖用下列方式可觀察/行爲主體: 我有其中顯示無處不在的應用爲背景的組成部分。 在一個顯示在該背景上的表單組件中,我想要 將來自用戶的數據和 使用此數據進行異步調用,並使用該異步調用的結果在該後臺組件中的方法
所以在我app.component.ts我有Subsribing到可觀察的數據提交在angular2
<app-header></app-header>
<backround-component></background-component>
<router-outlet></router-outlet>
LN在我的我的app.routing.ts我:
const appRoutes: Routes = [
{ path: '',
redirectTo: 'home',
pathMatch: 'full'},
{ path: 'home', component: HomeComponent },
{ path: 'form-component', component: Form component where the user submits the data },
];
在外形component.html我:
<button class="btn--submit" (click)="onClick()">Click</button>
所以我試圖做的是:
1)對數據的提交表單組件調用從服務,建立了基於提交的數據的請求的方法:
onClick = function() {
this.service.makeAsynchCall(dataFromTheUser);
}
2)請到遠程API異步調用:
public makeAsynchCall(dataFromTheUser): Observable<any> {
// build the request based on the data
return Observable.create((observer) => {
this.someRemoteService.route(request, (response, status) => {
observer.next(response);
});
});
}
3)訂閱在後臺的組件,可觀察到在ngBeforeView生命週期鉤,這樣我可以使用第響應E:
ngBeforeView {
this.service.makeAsynchcall().subscribe(response =>
this.useTheResponse(response);
);
}
我假設的情況是,在這樣的背景分量非同步調用首先被強制調用加載,那麼它有力地調用,從用戶希望數據的方法,該數據未提交然而,請求失敗。 我還嘗試了另一種方案 - 使用BehaviourSubject/AsyncSubject作爲連接件,利用observer和Observable的角色,並在數據到達時通知其他訂戶,並且這些訂戶不起作用。 非常感謝您的幫助。
更新:嘗試基於以下
這裏的答案例如下面就是我試圖做的。在我的訂戶中,next()方法只是打印收到的值。一切是相同的(除了我沒有創建數據模型)
public update(data)
{
let request = {}; // build request object based on 'data'
this.source.next(data); // subscriber doesn't get the value (not printed)
// make async call
this.service.asyncCall(request, (response, status) => {
if (status == OK) {
console.log('got result'); // this prints, so we get here
this.source.next(data); // subscriber doesn't get the value (not printed)
}
});
}
你好並且非常感謝您的幫助。我嘗試了你的建議,並且它一直運行良好,直到用戶從源頭獲取價值。你有沒有機會知道爲什麼用戶無法從源頭獲得結果?我已經用我到目前爲止的更新了我的問題。謝謝! – tomcat
採取有關的用戶沒有得到通知的變化的NWE問題看看這個問題:https://stackoverflow.com/questions/37150891/issue-with-rxjs-behaviorsubjects-subscriber-not-being-notified-of-值變化 – Filkolev