由服务通知的组件

问题描述 投票:0回答:2

我有一项与第三方服务沟通的服务。该服务由应用程序中的多个组件执行。我想在服务失败时通知通用通知组件(“DoSomethingWhenFails”函数)。目前,app.component中引用了通用通知组件,并将服务注入该组件。

我想到了将在服务中发出的eventEmitter之类的东西,但是在注入服务时我并不熟悉这种模式。这样做的最佳方式是什么?看我的代码:

app.component.html:

<notify #messageBox ></notify>

组件:

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

@ViewChild('messageBox') messageBox : notify;

constructor(private someService: SomeService ) 

通用通知组件:

export class notification 
{
  ShowNotificationWhenTheServiceFails()
  {
    DoSomethig();
  }
}

服务:

@Injectable({
  providedIn: 'root'
})


export class Service{

doSomething(): Observable<any> {
return this.http.get<AA>(URL, options).pipe(
     connectToThirdPArtyService();
  }),
   DoSomethingWhenFails();
  );
}
angular angular-services angular2-observables
2个回答
1
投票

每当服务调用中发生错误时,您都应该使用rxjs Subject来发出值。你应该调用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);
  );
}

在您的组件中,您应该使用subscribe方法按如下方式监听notify $ subject,每当使用next方法发出值时,组件中的subscribe方法被调用,您可以在notify$订阅中执行某些操作

export class notification implements OnInit {

  constructor(public service:Service) { }

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

}

2
投票

您可以使用行为主题来执行此操作。

service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

private messageSource = new BehaviorSubject('0');
currentMessage = this.messageSource.asObservable();

constructor() { }

changeNotification(number) {
this.messageSource.next(number)
}

}

parent.component.ts(您的案例中的通知组件)

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `,
  styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.changeNotification.subscribe(number => this.number = number)
  }

}

当失败时你可以推动行为主题,如,

constructor(private data: DataService) { }

 onFailure() {
    this.data.changeNotification("1")
  }

您可以在服务级别获得一个数字,并在失败时增加它,然后推送它或任何想要的方式。

© www.soinside.com 2019 - 2024. All rights reserved.