gpt4 book ai didi

javascript - Angular 2服务从组件调用方法

转载 作者:行者123 更新时间:2023-11-30 09:29:12 24 4
gpt4 key购买 nike

甚至可以让服务调用组件方法吗?

我的应用程序组件

export class MyAppComponent {
public value;
...
public setValue(payload){
this.value = payload;
}
}

我的应用程序服务

@Injectable()
export class MyAppService {
private myAppComponent: MyAppComponent;
private apiClientService: ApiClientService

// ...
After i make an PUT http call, the body from the response is my new "value"
// ...

putValue(payload: JSON){

return this.apiClientService.putAPIObject(payload).then((response) => {
this.myAppComponent.setValue(response);
});
}
}

这导致 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'setValue' of undefined .

有人可以解释我做错了什么吗?提前致谢。

编辑:由于人们提示我的方法,如果有人能向我解释什么是处理这个问题的最佳方法,我完全可以从头开始。

我从 api 获取值,更改它们,然后将它们放回 api。我不想再次调用 get,所以我在 Put 调用的响应中获得了我想要的新数据。

调用从组件-->组件服务-->apiclient服务

我想问题是我在起点和终点之间有一个额外的服务。

编辑 2:我试图避免 component service并使它对我有用 component --> apiclient service

即使是这个灵魂也在为我工作,但我现在有点不喜欢它,因为我必须从我的 api 中复制和粘贴很多代码来与其他对象进行相同的“操作”。例如,我让它适用于图片组件,但我的电影组件也需要它。如果我经常在一个项目中编写相同的代码,通常这是一件坏事,或者不是?

最佳答案

至少有几种方法可以解决这个问题,但希望这能给你一个开始。接受反馈和更正。

使用可观察对象

让服务拥有值(value)变化的知识并发出变化。该组件监听服务上的 EventEmitter 1 以对值变化使用react。 (另请参阅:Creating and returning Observable from Angular 2 Service)

MyAppService

import { Subject } from 'rxjs/Subject';

@Injectable()
export class MyAppService {
private valueSource = new Subject<any>();
public valueUpdate$ = this.valueSource.asObservable();

putValue(payload: JSON){
return this.apiClientService.putAPIObject(payload).then((response) => {
/** here **/
this.valueUpdate$.next(response);
});
}
}

MyAppComponent

export class MyAppComponent {
public value;
private valueSubscription;

constructor(private _myAppService: MyAppService) {}

ngOnInit() {
/** and here **/
this._myAppService.valueUpdate$.subscribe((p) => this.setValue(p));
}
...
public setValue(payload){
this.value = payload;
}
}

注册组件

回答原来的问题,想法是向服务注册组件,以便它可以根据需要调用组件。您可以通过依赖注入(inject)提取引用,但不推荐这样做(例如,如果您的原始组件引用被破坏怎么办?)

MyAppService

@Injectable()
export class MyAppService {
private myAppComponent: MyAppComponent;

/** here **/
registerMyApp(myApp: MyAppComponent) {
this.myAppComponent = myApp;
}

putValue(payload: JSON){
return this.apiClientService.putAPIObject(payload).then((response) => {
this.myAppComponent.setValue(response);
});
}
}

MyAppComponent

export class MyAppComponent {
public value;

/** and here **/
constructor(myAppService: MyAppService) {
myAppService.registerMyApp(this);
}
...
public setValue(payload){
this.value = payload;
}
}
  1. 感谢 AJT_82 指出 Angular 不希望开发人员在服务上使用 EventEmitter:What is the proper use of an EventEmitter? .

关于javascript - Angular 2服务从组件调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47418009/

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