0

在这种情况下如何管理错误块 - 服务中的错误管理并发送到组件

这里在第一次加载时将数据存储在 BehaviorSubject 中,并从我需要的地方订阅数据。

只是在应用程序运行时从 app.component 初始化预加载功能 - 但我想在这里知道它是否有错误

//**app component**
//just initializing preload function() when the app runs - but I want to know here if its an error
ngOnInit() {
    this.projectsService.preloadAllProjects();
}




// == services ==

//preload all projects
  preloadAllProjects(){
    this.http.get('/api/project/allprojects').pipe( map( response => response )).subscribe(result => {
      this.allProjectsBehavior.next(result);
    });
  };
4

2 回答 2

1

如果您想遵循主题路径:

//**app component**
//just initializing preload function() when the app runs - but I want to know here if its an error
ngOnInit() {
    this.projectsService.preloadAllProjects();
    this.projectService.error$.subscribe(error => console.log(error));
}




// == services ==

//preload all projects
  error$: Subject<string> = new Subject();
  preloadAllProjects(){
    this.http.get('/api/project/allprojects').pipe( map( response => response )).subscribe(result => {
      this.allProjectsBehavior.next(result);
    }, error => this.error$.next(error);
  };

或者您基本上可以从以下位置返回 Observable preloadAllProjects

//**app component**
//just initializing preload function() when the app runs - but I want to know here if its an error
ngOnInit() {
    this.projectsService.preloadAllProjects().subscribe(success => {}, error => console.log(error))
}




// == services ==

//preload all projects
  error$: Subject<string> = new Subject();
  preloadAllProjects(){
    return new Observable(observer => {
    this.http.get('/api/project/allprojects').pipe( map( response => response )).subscribe(result => {
      this.allProjectsBehavior.next(result);
      observer.next(true);
      observer.complete();
    }, error => observer.error(error);
   });
  };
于 2019-05-21T07:41:13.710 回答
1

您可以添加catchError运算符,也可以将第二个函数传递给您的subscribe函数。

解决方案1:

preloadAllProjects(){
  this.http.get('/api/project/allprojects').pipe(
    catchError(err => console.error(err)), 
    map( response => response )).subscribe(result => {
      this.allProjectsBehavior.next(result);
  });
};

解决方案2:

preloadAllProjects(){
  this.http.get('/api/project/allprojects').pipe(
    map( response => response )).subscribe(result => {
      this.allProjectsBehavior.next(result);
    },
    error => console.error(error)
    );
};
于 2019-05-21T07:43:12.700 回答