簡體   English   中英

當服務中的數據發生變化時如何通知組件

[英]How to notify component when data changes in service

我有一個自定義錯誤處理程序服務,每當應用程序出現錯誤時都會收到通知,現在我想通知組件有關錯誤的信息,以便組件向用戶顯示錯誤對話框,我嘗試過事件發射器,觀察者,但是什么都沒有通知組件......

這是我的服務...

@Injectable()
export class ErrorHandlerService implements ErrorHandler {
  public apiError: Subject<any> = new BehaviorSubject(false);
  apiError$ = this.apiError.asObservable();
  constructor(private errorLogService: ErrorLogService
  ) {}

  handleError(error) {
    this.apiError.next(error); 
    console.log("ERROR = " + error);
  };}

而組件...

@Component({
  selector: 'app-error-log',
  templateUrl: './error-log.component.html',
  styleUrls: ['./error-log.component.scss'],
  providers: [ErrorLogService]
})
export class ErrorLogComponent implements OnInit {

  constructor(
    private errorHandlerService: ErrorHandlerService

  ) {
    this.errorHandlerService.apiError$.subscribe(data => {

      alert("error in component = " + data);

    });
  }

  onNoClick(): void {
    // this.dialogRef.close();
  }

  ngOnInit() {
    this.errorHandlerService.apiError$.subscribe(data => {

      alert("error in component = " + data);

    });
  }

}

具有以下格式的方法可以給出服務執行成功與否的輸出。 希望以下代碼能幫到你

   //Code in service.ts
   @Injectable()
    export class ErrorHandlerService implements ErrorHandler {
        public apiError: Subject<any> = new BehaviorSubject(false);
        apiError$ = this.apiError.asObservable();
        constructor(private errorLogService: ErrorLogService
        ) { }

        private handleError(error) {
             return Observable.throw(error.json().msg || 'Server error');
        }
        _forgotPassword(userId, passwords, isResetPwd) {
            return this.http.post(this.forgotPasswordUrl,
                {
                    userId: userId,
                    passwords: passwords,
                    isResetPwd: isResetPwd
                })
                .map(res => res.json())
                .catch(this.handleError);
        }
    }

 //Code in component class file

  this.errorHandlerService._forgotPassword(userId, passwords, isResetPwd).
  subscribe(data => {
    // Code here.....
   });

這就是我修復它的方式...

應用程序組件.html

<error-log></error-log>

錯誤日志組件

import { Component, OnInit } from '@angular/core';
import { ErrorLogService } from './error-log.service';

@Component({
  selector: 'error-log',
  templateUrl: './error-log.component.html',
  styleUrls: ['./error-log.component.scss']
})
export class ErrorLogComponent implements OnInit {

  constructor(private errorLogService: ErrorLogService) { }

  ngOnInit() {
    this.errorLogService.apiEvent.subscribe(data =>{

            alert("error in errorlog component through errorLogService event emitter = " + data);
          })

          this.errorLogService.apiError$.subscribe(data =>{
            alert("error in errorlog component errorLogService  = " + data);
          })
  }

}

錯誤處理程序服務

import { Injectable, ErrorHandler} from '@angular/core';
import { ErrorLogService } from './error-log.service';

    @Injectable()
    export class ErrorHandlerService implements ErrorHandler {
      constructor(private errorLogService: ErrorLogService
      ) {}

      handleError(error) {
        this.errorLogService.setError(error);
      };}

錯誤日志服務

import { Injectable, ErrorHandler, EventEmitter, Output} from '@angular/core';
import { EventListener } from '@angular/core/src/debug/debug_node';
import { ReplaySubject} from 'rxjs/Rx';

@Injectable()
export class ErrorLogService  {
  public apiError: ReplaySubject<any> = new ReplaySubject();
  public apiEvent:EventEmitter<any> = new EventEmitter();
  public apiError$ = this.apiError.asObservable();
  constructor() {
    // super();
  }

  setError(error){
    this.apiEvent.emit(error);  
     this.apiError.next(error); 
    // super.handleError(error);
    console.log("ERROR = " + error);
  } }

不知道為什么我不能直接從 error-handler.service 引發事件

如果您在服務收到錯誤后初始化組件,那么他只能發出在他的 init 之后收到的錯誤。

用戶 ReplaySubject 也發出所有以前的錯誤

@Injectable()
export class ErrorHandlerService implements ErrorHandler {
  public apiError: ReplaySubject<any> = new ReplaySubject();
  apiError$ = this.apiError.asObservable();
  constructor(private errorLogService: ErrorLogService
  ) {}

  handleError(error) {
    this.apiError.next(error); 
    console.log("ERROR = " + error);
  };}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM