在我的代碼中,我試圖使用 observables 映射字串陣列,我想在輸入中查看該值。我在控制臺上列印了我的代碼,我可以看到陣列,但我無法將它分配給輸入欄位。我也收到錯誤Type 'Subscription' is missing the following properties from type 'Observable<any[]>': source, operator, lift, subscribe, and 3 more.
,我想查看其中的陣列元素,但我看到的是{{ slider$ | async }}
. 我應該怎么做才能修復我的代碼?
HTML:
<input type="input" value="{{ slider$ | async }}" />
TS:
const slides = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4'];
let slider$: Observable<any[]>;
slider$ = of(slides).pipe(map((response) => {return response;})).subscribe(console.log);
uj5u.com熱心網友回復:
堆疊閃電戰
import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map, tap } from 'rxjs/operators';
@Component({
selector: 'my-app',
template: `
<input type="input" value="{{ slider$ | async }}" />
`,
})
export class AppComponent {
slides: string[] = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4'];
slider$: Observable<string> = of(this.slides).pipe(
tap(console.log), // ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4']
map((arr: string[]) => {
return arr[0]; // map to 1st element of the array
}),
tap(console.log) // 'Slide 1'
);
}
當您這樣做時{{ slider$ | async }}
,異步管道正在訂閱(并在組件銷毀時清理訂閱)到 observable slider$
。在您的代碼中,您直接訂閱,以便slider$
成為訂閱而不是預期的 Observable,因此會出現錯誤。如果您希望通過流進行部分除錯,可以使用tap
pipeable 運算子。這也用于副作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/524783.html