如何在 Angular 6 / Typescript 中延迟可观察对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50788571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delay an observable in Angular 6 / Typescript
提问by Jimmyt1988
I have the following method GetCurrentUserDelayedTest
that i wanted to put a delay on. I have left the original implementation here GetCurrentUser
to demonstrate how i was originally using it:
我有以下GetCurrentUserDelayedTest
我想延迟的方法。我在此处留下了原始实现GetCurrentUser
来演示我最初是如何使用它的:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { User } from '../models/user';
export class UserService {
// Normal method without delay
public GetCurrentUser(): Observable<User>
{
return of(new User(""));
}
// Method with delay attempt at code
public GetCurrentUserDelayedTest(): Observable<User>
{
var observable = new Observable<User>((observable) => {
setTimeout(() => {
return observable.complete();
}, 2000);
});
observable.subscribe(() => {
return of(new User(""));
});
return observable;
}
}
I'm trying to delay the method from returning its data by 2 seconds.
我试图将方法从返回数据延迟 2 秒。
What am i doing wrong? I'm brand new to angular 6 and typescript.
我究竟做错了什么?我是 angular 6 和 typescript 的新手。
I'm calling it like this:
我这样称呼它:
this.userService.GetCurrentUserDelayedTest()
.subscribe((currentUser) => {
this.loadingGameState = false;
});
The "Loading App" part remains on screen (no errors are thrown) rather than updating the view to show "Welcome"
“正在加载应用程序”部分保留在屏幕上(不会引发错误)而不是更新视图以显示“欢迎”
<div *ngIf="loadingGameState">Loading App</div>
<div *ngIf="!loadingGameState">
Welcome
</div>
Edit:
编辑:
Argument of type 'Promise' is not assignable to parameter of type 'OperatorFunction'. Type 'Promise' provides no match for the signature '(source: Observable): Observable'.
“Promise”类型的参数不可分配给“OperatorFunction”类型的参数。类型 'Promise' 与签名 '(source: Observable): Observable' 不匹配。
回答by izmaylovdev
回答by Ilya Scharrenbroich
A more detailed example using HttpClient:
使用 HttpClient 的更详细示例:
of(null).pipe(
delay(2000),
flatMap(() => {
return this.http.post<any>(url, params);
})
);
回答by Bogdan Bogdanov
https://stackblitz.com/edit/angular-mznw5m?file=src%2Fapp%2Fuser.service.ts
https://stackblitz.com/edit/angular-mznw5m?file=src%2Fapp%2Fuser.service.ts
Use in the declaration of the Observable
observable.next()
so you can trigger the subscribers.
在 的声明中使用,Observable
observable.next()
以便您可以触发订阅者。