Angular-从组件更新服务的属性

时间:2018-08-01 23:41:11

标签: angular service dependency-injection error-handling custom-error-handling

我有一个带有appName属性的服务。当我的组件执行POST时,我试图将组件的名称传递给服务的appName属性,从而在Service中对其进行更新,以便当服务稍后调用此属性时,它具有我发送的新值来自组件。

但是,我无法更新服务的appName属性-它与服务中最初定义的属性相同:

error-logger.service.ts

  constructor(private http: HttpClient) { 

  };

    appName = "initialName";

//logError function fires on error from GlobalErrorHandlerService, logging errors and passing the new appName value from component.
    logError() {
    //below should log the new appName (from component), not the initial
    console.log("Application:" + this.appName);
    }

}

my-component.component.ts

import { Component, OnInit } from '@angular/core';
import { ErrorLoggerService } from '../../../core/services/error-logger.service';
import { Router, ActivatedRoute } from '@angular/router';

...

  constructor(
    private errorLoggerService: ErrorLoggerService,
    private route: ActivatedRoute,
    private router: Router
    ) {
      console.log("COMPONENT NAME: " + this.route.component.name);
    }



  ngOnInit() {
    this.errorLoggerService.appName = "NewAppName";
    this.errorLoggerService.postData(JSON.stringify(myData))
    .subscribe(
      data => console.warn(data),
      error => {throw error},
      () => console.log("empty")
    );
  }

global-error-handler.service.ts

import { Injectable, ErrorHandler, Injector } from '@angular/core';
import {ErrorLoggerService} from '../services/error-logger.service';
import { HttpErrorResponse } from '@angular/common/http';

// Global error handler for logging errors
@Injectable()
export class GlobalErrorHandlerService extends ErrorHandler {
    constructor(private injector : Injector) {


        super();
    }

    handleError(error: any) {
      let loggerService = this.injector.get(ErrorLoggerService);
      loggerService.logError(error)    
      .subscribe(
        data => console.warn(data),
        error => {throw error},
        () => console.log("empty")
      );

  }
}

如何从组件中正确更新服务的属性?我根本上有问题,或者可能与我在error-logger.service.ts

中所做的RXJS /自定义错误处理的异步性质有关

1 个答案:

答案 0 :(得分:1)

我认为该代码将为您工作:

第一个“ error-logger.service.ts”:

中转换您的appName
public appName = new BehaviorSubject<string>('initialName')

logError(error) {
   return appName.pipe(tap(appName => console.log(appName)))
   // or
   //return appName.pipe(switchMap(appName=> {
   //     console.log(appName)
   //     return of('{data}')
   // }))
}

第二个my-component.component.ts:

this.errorLoggerService.appName.next('otherName')

第三个GlobalErrorHandlerService:

loggerService.logError(error)    
  .subscribe(
    appName => console.warn(appName),
    // or data => console.warn(data)
    error => {throw error},
    () => console.log("empty")
  );

我的思想正常,希望如此:)