Observable.map setTimeout函数,返回类型为角度5

时间:2018-04-06 12:42:47

标签: angular rxjs angular2-observables

我想在Observable.map函数中等一下,然后返回一个值

我的代码是:

public loginRequest(userCredentials: any): Observable<TSUser | undefined> {

    return this.http.post<TSUser>(this.serviceURL + '/login', userCredentials).map((response: any) => {

        window.setTimeout(() => {
            this.initWithCookie();
            return this.principal;
        }, 300);
        //error TS2322: Type 'Observable<void>' is not assignable to type 'Observable<TSUser | undefined>'. Type 'void' is not assignable to type 'TSUser | undefined'.

    });

};

如何使用setTimeout函数返回正确的Observable类型。用我的代码我得到错误     error TS2322: Type 'Observable<void>' is not assignable to type 'Observable<TSUser | undefined>'. Type 'void' is not assignable to type 'TSUser | undefined'.

如果我这样做:

public loginRequest(userCredentials: any): Observable<TSUser | undefined> {

    return this.http.post<TSUser>(this.serviceURL + '/login', userCredentials).map((response: any) => {

        return Observable.timer(300).map(() => {
                this.initWithCookie();
                return this.principal;
            }).take(1);
    });

};

我收到错误     error TS2322: Type 'Observable<Observable<TSUser | undefined>>' is not assignable to type 'Observable<TSUser | undefined>'.

解决方案 根据马丁的答案,我的工作代码是

public loginRequest(...): Observable<TSUser | undefined> {

        return this.http.post<TSUser>(...).delay(300).concatMap(response => Observable.of(this.initWithCookie()));

};

(我希望等待300ms 之前我执行我的函数中的代码)

2 个答案:

答案 0 :(得分:2)

不使用setTimeout更容易,让RxJS使用delay()运算符为您带来延迟:

return this.http.post<TSUser>(...)
  .concatMap(response => Observable.of(response).delay(300));

您可以使用setTimeout,但之后必须使用Observable.create(observer => {})并将setTimeout内的结果发送到observer.next(...),这会造成不必要的复杂。

答案 1 :(得分:0)

使用RxJS v6,已更改了运算符的导入和使用语法。

import { of } from 'rxjs';
import { delay, concatMap } from 'rxjs/operators';

return of({delay_time: 3000}).pipe(
  concatMap(response => of('Delayed by: ' + response.delay_time + ' ms').pipe(delay(response.delay_time)))
);