简体   繁体   中英

Angular - Update a service's property from a component

I've got a service with an appName property. When my component does a POST, I'm trying to pass the component's name to the service's appName property, thus updating it in the Service, so that when the service calls this property later, it has the new value I sent from the component.

However, I can't get the service's appName property to update - it stays the same as initially defined in the service:

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")
      );

  }
}

How can I properly update the service's property from the component? Either I've got something fundamentally wrong, or maybe it has to do with the asynchronous nature of the RXJS/custom error handling I'm doing in the error-logger.service.ts

i think this code gonna work for you:

First 'error-logger.service.ts':

Convert your appName in

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}')
   // }))
}

Second my-component.component.ts:

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

Third GlobalErrorHandlerService:

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

I my mind works, hope so works :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM