簡體   English   中英

無法將可觀察數據分配給 angular 中的局部變量

[英]Can not assign observable data to local variable in angular

我的服務

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { HttpClient,HttpParams } from '@angular/common/http';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }
  isAdmin;
  getLogIn(email:string,password:string):Observable<boolean>{
    let params = new HttpParams().set("userEmail",email).set("userPassword", password);
    return this.http.get<boolean>("http://localhost:8080/user/login",{params: params});
     }
}

我的訂閱電話

 email:string="";
  password:string="";
  adminFlag:boolean=false;

  login(event: any) {
    console.log(this.adminFlag);
    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
    console.log(this.adminFlag);
    if(this.adminFlag){
      console.log("INSIDE IF")
        this.router.navigate("../../home");
    }
  }

當我在控制台中登錄 data var 時,我得到的原始數據為

true

但我無法將它分配給這個布爾值“adminFlag”它已更改為未定義

我錯過了什么......?

API 返回一個布爾值......我需要分配那個布爾值......

HTTP GET是一個異步請求 這意味着您在設置變量adminFlag之前正在讀取它。 在回調中移動路由以設置值並使用它。 在 HTTP 請求中包含錯誤回調也是一種很好的做法。 這應該有效:

login(event: any) {
  this.userService.getLogIn(this.email,this.password).subscribe(
    data => {
      this.adminFlag = data; 
      if (data) {
        this.router.navigate("../../home");
      }
    },
    error => {
      console.error('getLogIn failed');
      // handle error...
    }
  );
}

執行時:

    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));

這意味着您希望 DATA 是一個布爾值。 它是一個可觀察的布爾值。 要獲得真正的布爾值,請使用管道函數,例如:

getLogIn(email:string,password:string):boolean{
  let params = new HttpParams().set("userEmail",email).set("userPassword", password);
  return this.http
    .get<boolean>("http://localhost:8080/user/login",{params: params})
    .pipe(map(data => data);
}

暫無
暫無

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

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