简体   繁体   English

无法将可观察数据分配给 angular 中的局部变量

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

My Service我的服务

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});
     }
}

My Subscribe call我的订阅电话

 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");
    }
  }

When i log in data var in console I am getting raw data as当我在控制台中登录 data var 时,我得到的原始数据为

true

but i couldn't assign it to this boolean "adminFlag" it is changed to undefined但我无法将它分配给这个布尔值“adminFlag”它已更改为未定义

Anything I missed...???我错过了什么......?

the API is returning a boolean..I need that boolean to be assigned... API 返回一个布尔值......我需要分配那个布尔值......

HTTP GET is an asynchronous request . HTTP GET是一个异步请求 Which means you are reading the variable adminFlag before it is being set.这意味着您在设置变量adminFlag之前正在读取它。 Move the routing inside callback to set the value and use it.在回调中移动路由以设置值并使用它。 Its also always good practice to include error callback in HTTP requests.在 HTTP 请求中包含错误回调也是一种很好的做法。 This should work:这应该有效:

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...
    }
  );
}

When you are executing:执行时:

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

it means that you expect DATA to be a boolean.这意味着您希望 DATA 是一个布尔值。 It's an observable boolean instead.它是一个可观察的布尔值。 To get the real boolean, use the pipe function, eg:要获得真正的布尔值,请使用管道函数,例如:

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