我有一個Angular(4)中的情況異步管道沒有綁定到ngAfterViewInit()
中設置的Observable,除非我使用Observable.interval(1000)
在構造函數中初始化它。如果我刪除了.interval
-部分,則當ngAfterViewInit()
運行時,異步管道將不會訂閱觀察值。異步管道不綁定到角度Observable
我想初始化的觀像這樣在類的頂部,但打破了功能:
resultStream: Observable<string>;
genderStream: Observable<number>;
我必須聲明它們是這樣的:那麼
// Weird fix: I need to add .interval(?) for async pipe to work later on...
resultStream: Observable<string> = Observable.interval(1000).map(() => "");
genderStream: Observable<number> = Observable.interval(1000);
我解決方案現在感覺有點不滿意,因爲我必須使用.interval()
設置。
問題是轉載於本plunker:https://plnkr.co/edit/q3TR5iszU1swFrTjajEa
點擊性別,並在輸入框中輸入一個整數,顯示的結果。
你能幫助我一個簡單/優雅的解決方案嗎? 謝謝。
完整的類是這樣的:
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, ChangeDetectionStrategy } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'my-app',
template: `
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<input #distance class="form-control" placeholder="Distance">
<button #femaleGender type="button" class="btn btn-default" [class.active]="(genderStream | async) === 1">Female</button>
<button #maleGender type="button" class="btn btn-default" [class.active]="(genderStream | async) === 0">Male</button>
</form>
</div>
<div class="col-md-6">
<h4>Result: {{ resultStream | async }}</h4>
</div>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements AfterViewInit {
// Weird fix: I need to add .interval(?) for async pipe to work later on...
resultStream: Observable<string> = Observable.interval(1000).map(() => "");
genderStream: Observable<number> = Observable.interval(1000);
@ViewChild('distance') distance: ElementRef;
@ViewChild('maleGender') maleGender: ElementRef;
@ViewChild('femaleGender') femaleGender: ElementRef;
ngAfterViewInit() {
let distance$ = Observable.fromEvent(this.distance.nativeElement, 'keyup')
.map((event: Event) => event.target)
.map((element: HTMLInputElement) => element.value)
.map(value => parseInt(value))
.filter(value => !isNaN(value));
// In the calculation 0 is used for males and 1 for females.
let male$ = Observable.fromEvent(this.maleGender.nativeElement, 'click').map(() => 0);
let female$ = Observable.fromEvent(this.femaleGender.nativeElement, 'click').map(() => 1);
let gender$ = Observable.merge(male$, female$);
this.genderStream = gender$;
this.resultStream = Observable.combineLatest(
distance$,
gender$,
(distance, gender) => calculateResult(distance, gender).toFixed(1)
);
}
}
const calculateResult = (distance: number, gender: number) => 18.38 + (0.033 * distance) - (5.92 * gender);
請把你的plunkr中的相關內容編輯到你的文章中。鏈接最終會過期,這會導致您的帖子對遇到類似問題的其他用戶或多或少無用。另外,你基本上要求有人試圖幫助跳過一些籃球來提供幫助。 –
完成。好點! – skovmand
我認爲它與ChangeDetectionStrategy.OnPush – skovmand