【发布时间】:2018-06-05 09:51:41
【问题描述】:
所以我有以下内容:
const getAllData = Observable.create( () => {
console.log(Date.now() + ' - Calling getallcontenttypes');
this.getAllContentTypes();
console.log(Date.now() + ' - Calling getalltaxonomysitecolumns');
this.getAllTaxonomySiteColumns();
});
getAllData.subscribe( () => {
console.log(Date.now() + ' - Subscribed, data loaded, calling router...');
this.router.navigateByUrl('/contenttype');
});
我的 const getAllData 中的函数工作,获取数据并处理它(使用额外的控制台日志,所以我知道有值并且它们通过这些函数运行)。
我现在想要做的是,一旦我的 getAllData 中的所有函数(现在为 2)完成获取和处理所有数据,我想重新路由到另一个视图。这 2 个函数 (getall...) 现在返回 void。这一切都在我的 ngOnInit() 中。
但到目前为止,似乎 .subscribe() 没有触发,或者我做错了。任何人都可以看到什么问题?
例如,这里是 getAllContentTypes 函数:
public getAllContentTypes() {
const jsonStringified = JSON.stringify(json);
this.contentTypeService.getAllContentTypes(jsonStringified).pipe(
operators.tap(res => this.convertJsonResultToArrayCT(res)))
.subscribe(res2 => this.storeInSessionStorage(res2, 'ContentTypes'));
}
public storeInSessionStorage(res: any, key: string) {
sessionStorage.setItem(key, JSON.stringify(this.contentTypeArray));
console.log(Date.now() + ' - Stored in sessionstorage: ' + key);
}
这是我在控制台中看到的图像:https://imgur.com/a/xQhaqjv。
编辑:
好的,所以我修改了我的函数以返回 Observables:
public getAllContentTypes(): Observable<ContentType> {
const jsonStringified = JSON.stringify(json);
this.contentTypeService.getAllContentTypes(jsonStringified).pipe(
operators.tap(res => this.convertJsonResultToArrayCT(res)))
.subscribe(res2 => this.storeInSessionStorage(res2, 'ContentTypes'));
return from(this.contentTypeArray);
}
我也这样编辑了我的代码:
const test = forkJoin(
this.getAllContentTypes(),
this.getAllTaxonomySiteColumns()
).subscribe( () => {
console.log(Date.now() + ' - Subscribed, data loaded, calling router...');
this.router.navigateByUrl('/contenttype');
});
但没有触发订阅。
【问题讨论】:
-
"[...] .subscribe() 似乎没有触发 [...]" 什么会触发它?您的 observable 没有发出任何值。
-
那么我必须在我的 getalldata 中更改什么?我的 2 个函数是否需要返回数据/值/Observable?我可以在调用 2 个 void 函数后返回一个值/可观察值吗?
-
一种方法是让你的两个函数都返回一个 observable,然后使用
forkJoin()。 -
好的,我会将我现在拥有的内容添加到我的 OP(作为 EDIT)中!
标签: angular observable publish-subscribe