簡體   English   中英

我應該如何在Angular中等待http請求完成?

[英]How should I wait for http request to complete in Angular?

我一直在努力學習Angular(Typescript)+ ASP Net Core,我不明白我應該如何等待observable完成。 基本上,我在后端創建了一個登錄服務,它可以工作。 但是,我試圖創建一個簡單的幫助程序,以便在客戶端更容易處理http響應。 問題是它運行了兩次:在第一個上它認為RequestResponse是未定義的(因為它跳過了http請求),而在第二個時,RequestResponse被填充並且它按預期工作。

這是Http助手:

 get<T>(url: string): Observable<T> {
    let options = this.doHeaders();
    return this.doSub(this.http.get(this.doUrl(url), options));
}

private doSub<T>(obs: Observable<Response>) {
    var ob1: Observable<T> = obs.map(this.extractData)
        .catch(this.handleError);

    return ob1;
}

這是RequestResponse:

export class RequestResponse {
   public error: string;
   public isOk: boolean;
   public code : StatusCode; 
}

這是服務:

@(Injectable)
export class RequestService {

constructor(
    private net: NetworkService,
    private loaderService: LoaderService,
    private storage: StorageService,
) {
}

login(email: string, password: string, rememberMe: boolean = false): RequestResponse {
    var r = new RequestResponse();

     // I need to make this wait
     this.net.get<LoginModel>(`Authentication/Login/${email}/${password}`).subscribe(t => {
            this.storage.token = t.token;
            this.storage.email = rememberMe ? email : null;
            this.storage.password = rememberMe ? password : null;
            this.storage.user = t.user;
            r.isOk = true;
            r.code = StatusCode.OK;
        },
        error => {
            r.isOk = false;
            switch (error.message) {
            case '403':
                    r.code = StatusCode.Forbidden; r.error = 'You've been suspended'; return;
            case '404':
                    r.code = StatusCode.NotFound; r.error = 'User not found'; return;
            case '406':
                    r.code = StatusCode.NotAcceptable; r.error = 'Invalid Email/Password'; return;
            default:
                r.code = StatusCode.InternalServerError; r.error = 'Internal Error'; return;
            }
        });

    // First time it is skipping all the way down, returning null
    return r;
   }
}

這是我試圖使用它的方式:

login() {

    this.loginResponse = this.requestService.login(this.email, this.password, this.rememberMe);
    console.log(this.loginResponse);
    if (!this.loginResponse.isOk) {
        this.toasterService.pop('error', 'Error', this.loginResponse.error);
        return;
    }
    this.router.navigateByUrl('/home');
}

我已經閱讀了Promises和Observables,我嘗試了很多更改,但第一個RequestResponse為null仍然是個問題。

我應該怎么處理這個?

建議您在組件中使用subscribe,而不是在服務中使用。 這樣,您將有更好的機制在訂閱完成時作出反應,並提供取消或取消訂閱的方法。

我的服務代碼

getProducts(): Observable<IProduct[]> {
    return this.http.get<IProduct[]>(this.productsUrl)
                    .pipe(
                        tap(data => console.log(JSON.stringify(data))),
                        catchError(this.handleError)
                    );
}

我的組件代碼

ngOnInit(): void {
    this.productService.getProducts().subscribe(
        (products: IProduct[]) => {
            this.products = products;
            // Any code to be run after the subscription is complete goes here
        },
        (error: any) => this.errorMessage = <any>error
    );
}

對於“完整”示例應用程序,請查看我的github存儲庫: https//github.com/DeborahK/Angular-GettingStarted

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM