gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:22:55 24 4
gpt4 key购买 nike

我有一个带有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/自定义错误处理的异步特性有关

最佳答案

我认为这段代码将为您工作:

第一个“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")
);

我在我的脑海里工作,希望也可以:)

关于angular - Angular-从组件更新服务的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51643660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com