组件被服务通知

Guy*_*y E 6 angular-services angular2-observables angular

我有一项与第三方服务通信的服务。该服务由应用程序中的多个组件执行。每当服务失败时(“DoSomethingWhenFails”函数),我希望在通用通知组件中收到通知。目前,通用通知组件在 app.component 中引用,并且服务被注入到该组件中。

我想到了类似 eventEmitter 的东西,它会在服务中发出,但是在注入服务时我不熟悉这种模式。最好的方法是什么?看我的代码:

应用程序组件.html:

<notify #messageBox ></notify>
Run Code Online (Sandbox Code Playgroud)

组件:

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
 styleUrls: ['./app.component.scss']
})
export class AppComponent  {

@ViewChild('messageBox') messageBox : notify;

constructor(private someService: SomeService ) 
Run Code Online (Sandbox Code Playgroud)

通用通知组件:

export class notification 
{
  ShowNotificationWhenTheServiceFails()
  {
    DoSomethig();
  }
}
Run Code Online (Sandbox Code Playgroud)

服务:

@Injectable({
  providedIn: 'root'
})


export class Service{

doSomething(): Observable<any> {
return this.http.get<AA>(URL, options).pipe(
     connectToThirdPArtyService();
  }),
   DoSomethingWhenFails();
  );
}
Run Code Online (Sandbox Code Playgroud)

Nit*_*jan 6

每当服务调用中发生错误时,您应该使用 rxjsSubject发出值。你应该调用该next()方法。

@Injectable({
  providedIn: 'root'
})
export class Service{
  public notify$ = new Subject<any>();
  doSomething(): Observable<any> {
  return this.http.get<AA>(URL, options).pipe(
     connectToThirdPArtyService();
  }),
   this.notify$.next(true);
  );
}
Run Code Online (Sandbox Code Playgroud)

在你的组件中,你应该使用该subscribe方法监听notify$主题,每当使用该方法发出一个值时next,组件中的订阅方法就会被调用,你可以在notify$订阅中执行一些操作

export class notification implements OnInit {

  constructor(public service:Service) { }

  ngOnInit() {
    this.service.notify$.subscribe(messages => {  DoSomethig(); });
  }

}
Run Code Online (Sandbox Code Playgroud)