第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

無(wú)法從 Angular 中的 EventEmitter 返回值

無(wú)法從 Angular 中的 EventEmitter 返回值

紅顏莎娜 2023-05-19 17:13:26
我想調(diào)用一個(gè)方法并在以下組件之間獲取結(jié)果。我知道有更好的方法,例如直接從服務(wù)調(diào)用方法,但我在我的列表組件中使用基本組件,我需要使用 EventEmitter 來(lái)執(zhí)行該方法并檢索其結(jié)果。那么,如何getServerData從基礎(chǔ)組件調(diào)用方法并通過(guò) EventEmitter 檢索其結(jié)果?當(dāng)我使用以下方法時(shí),它返回未定義?;A(chǔ)組件:@Output() request: EventEmitter<any> = new EventEmitter<any>();list() {    // code omitted for brevity    const result = this.emitDataRequest(index);    return result;}emitDataRequest(index) {    return this.request.emit(index);}列表組件:request(index) {    return this.getServerData(index);}getServerData(index): Observable<ListOfEmployee> {    return this.demoService.get(index);}
查看完整描述

1 回答

?
慕虎7371278

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊

EventEmitter 不能有返回值。據(jù)我所知你可以做兩件事。


@輸入回調(diào)

可以將方法傳遞給您的子組件并在那里使用它。


例如。


父組件:


// HTML

<app-sub [parentHook]="hook.bind(this)"></app-sub>


// TS

hook(value) {

  return value;

}

子組件


// HTML

<button (click)="getValueFromHook()">Click me!</button>


// TS

@Input() parentHook: () => number;


public getValueFromHook(): number {

  const valueFromHook = this.parentHook.call(this, 20);

  console.log(valueFromHook);

}

在您的情況下,您可以在此處返回一個(gè) Observable。


@輸入輸出

您可以將數(shù)據(jù)作為 an 傳遞@Input并在發(fā)出事件時(shí)更改它。在您的子組件中,您可以處理ngOnChanges上的更改事件。


例如:


父組件:


// HTML

<app-sub

  [data]="data"

  (request)="handleRequest($event)">

</app-sub>


// TS

public data = 5;


public handleRequest(request) {

  this.data = request + this.data;

}

子組件


// HTML

<button (click)="request.emit(20)">Click it!</button>


// TS

@Input() data: number;

@Output() request = new EventEmitter();


ngOnChanges(changes: SimpleChanges) {

  console.log(this.data);

}

我希望這對(duì)您有用。


@Input & @Output 與 Observables

與前面的示例相同,但使用可觀察對(duì)象,這樣您就不必使用 onChanges 生命周期


例如:


父組件:


// HTML

<app-sub

  [data$]="data"

  (request)="handleRequest($event)">

</app-sub>


// TS

public data = new Subject();


public handleRequest(index) {

  // here you can do your request to fetch some data and fill in 

  // the data$ observable with the result

  this.fetchSomeDataBasedOnIndex(index).subscribe(result => {

    this.data.next(result)

  });

}

子組件


// HTML

<button (click)="request.emit(20)">Click it!</button>


// TS

@Input() data$: Subject;

@Output() request = new EventEmitter();


ngOnInit(): void {

  this.data$.subscribe(d => console.log(d))

}


查看完整回答
反對(duì) 回復(fù) 2023-05-19
  • 1 回答
  • 0 關(guān)注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)