gpt4 book ai didi

javascript - 带事件发射器的触发功能

转载 作者:行者123 更新时间:2023-12-02 21:12:14 24 4
gpt4 key购买 nike

是否可以使用 EventEmitter 从当前组件触发另一个组件中的函数(作为回调)?例如,在我完成 API 请求后,会出现成功函数,如下所示:

@Output() afterAPIRequest = new EventEmitter();

handleSuccess() {
this.afterAPIRequest.emit();
}

现在,我可以在另一个组件中以某种方式捕获它并触发另一个函数,就像这样吗?

// when emitted, run this

refreshListIfEmitted() {
this.refreshMyList();
}

最佳答案

使用服务

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable()
export class MessageService {
private _message: Subject<any>;

constructor() {
this._message = new Subject();
}

get changes(): Observable<any> {
return this._message.asObservable();
}

set message(message: any) {
this._message.next(message);
}
}

组件一

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.scss'],
})
export class OneComponent {
constructor(private _http: HttpClient, private _message: MessageService) { }

apiRequest(): void {
this._http.get('end-point').subscribe(value => this._message.message = value);
}
}

第二部分

import { Component } from '@angular/core';

@Component({
selector: 'app-two',
templateUrl: './two.component.html',
styleUrls: ['./two.component.scss'],
})
export class TwoComponent {
constructor(private _message: MessageService) {
this._message.changes.subscribe(value => console.log(value));
}
}

关于javascript - 带事件发射器的触发功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61059170/

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