【问题标题】:Subscribe is not being triggered on Observable.create object订阅未在 Observable.create 对象上触发
【发布时间】: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


【解决方案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

【讨论】:

  • Nvm 我会继续寻找!
猜你喜欢
  • 2018-07-16
  • 1970-01-01
  • 2019-09-18
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
相关资源
最近更新 更多