这是我的代码:
import {Component} from "@angular/core";
import {Subject} from "rxjs/Subject";
import {Observable} from "rxjs/Observable";
import "rxjs/add/observable/interval";
import "rxjs/add/observable/merge";
import "rxjs/add/operator/map";
import "rxjs/add/operator/startWith";
import "rxjs/add/operator/scan";
import "rxjs/add/operator/mapTo";
@Component({
selector: 'app-root',
template: `
<button (click)="click$.next()">Update</button>
<h1>{{clock | async | date:'yyyy-MM-dd HH:mm:ss'}}</h1>
`
})
export class AppComponent {
click$ = new Subject<any>();
clock;
constructor() {
this.clock = Observable.merge(
this.click$.mapTo('hour'),
Observable.interval(1000).mapTo('second')
)
.startWith(new Date())
.scan((acc: Date, curr) => {
const date: Date = new Date(acc.getTime());
if (curr === 'hour') {
date.setHours(date.getHours() + 1);
}
if (curr === 'second') {
date.setSeconds(date.getSeconds() + 1);
}
return date;
});
}
}
&#13;
我在startWith(新日期())上遇到此错误,但是当我更改&#34; this.click $ .mapTo(&#39; hour&#39;)&#34 ; to&#34; this.click $&#34;,此错误消失了。 任何人都可以说出了什么问题吗?
答案 0 :(得分:0)
Observable.merge
将多个可观察对象转换为单个可观察对象。当您使用以下代码时,返回类型为Observable<any,string>
this.clock = Observable.merge(
this.click$,
Observable.interval(1000).mapTo('second')
)
但是当您使用以下代码段时,返回类型为Observable<string,string>
,以便scan
运算符接受字符串作为第一个参数并给出错误
this.clock = Observable.merge(
this.click$.mapTo('hour'),
Observable.interval(1000).mapTo('second')
)