订阅未在Observable.create对象上触发

时间:2018-06-05 09:51:42

标签: angular observable publish-subscribe

所以我有以下内容:

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)都完成了&处理所有数据,我想重新路由到另一个视图。那两个函数(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');
  });  

但订阅并未触发。

1 个答案:

答案 0 :(得分:1)

使用create()方法创建observable时,必须将观察者作为参数传递,以便稍后可以在其上调用next(),error()或complete(),例如

const getAllData = Observable.create( observer => { 
                                     observer.next('123');
                                    });

当代码订阅这个observable时,它必须传递一个函数来处理发出的值,并且可选地传递错误和完成,即观察者例如

getAllData.subscribe(value => console.log(value));  // prints 123

我在这里有一个工作代码示例:https://codepen.io/yfain/pen/xLaMdN?editors=1012

相关问题