在subscribe()中设置后,Angular组件属性无法解释地保持为“未定义”

问题描述 投票:0回答:1

让我说一下是,我正在使用箭头功能保留“ this”的范围]](据我所知,还是这样)。

我在组件上有两个属性:

IsAdmin(布尔值)currentRole(字符串)

我进行了api调用,以通过Angular的HttpClient从我的后端获取用户角色,并且我有一个回调subscription-method,它会使用结果更新上述属性。

但是,尽管我可以将角色值分配给currentRole,但是即使分配了其他属性IsAdmin仍未定义,并且通过chrome插件在f12调试器或Visual Studio代码中也没有出现错误。

        import { Component, OnInit } from "@angular/core";
    import { AuthorizeService, IUser } from "../authorize.service";
    import { Observable } from "rxjs";
    import { map, tap } from "rxjs/operators";
    import { HttpClient } from "@angular/common/http";

    @Component({
      selector: "app-login-menu",
      templateUrl: "./login-menu.component.html",
      styleUrls: ["./login-menu.component.scss"]
    })
    export class LoginMenuComponent implements OnInit {
      isAuthenticated: Observable<boolean>;
      public userName: Observable<string>;

      IsAdmin : boolean;
      currentRole : string;

      constructor(private authorizeService: AuthorizeService, private http : HttpClient) {

      }

      ngOnInit() {
        this.isAuthenticated = this.authorizeService.isAuthenticated();
        this.userName = this.authorizeService.getUser().pipe(map(u => u && u.name));
        const endpoint = '.../api/User/User/GetRoles';

        this.authorizeService.getUser()
          .subscribe(data => {
             this.userNameSignedIn = data.name;
          });

        this.http.get<string[]>(endpoint).
          subscribe(result => {
            this.currentRole = result[0];
            console.log("this.currentRole ", this.currentRole); //prints "admin"
            this.IsAdmin == result.includes("admin");
            console.log("this.IsAdmin", this.IsAdmin); //prints "undefined"
          }, error => console.error(error));
      }
    }

控制台输出如下:

logon-menu.component.ts:37 this.currentRole  admin
logon-menu.component.ts:39 this.IsAdmin undefined

这到底是怎么回事?我究竟做错了什么?

让我只是说一声就可以了,我正在使用箭头功能保留“ this”的范围(据我所知还是如此)。我的组件上有两个属性:IsAdmin(布尔值)currentRole(...)>

javascript angular typescript angular-components angular-httpclient
1个回答
0
投票

subscribe中的问题是您正在使用==(比较)而不是=(分配)

          subscribe(result => {
            this.currentRole = result[0];
            console.log("this.currentRole ", this.currentRole); //prints "admin"
            this.IsAdmin == result.includes("admin"); //<-- here is an error
            console.log("this.IsAdmin", this.IsAdmin); //prints "undefined"
          },
© www.soinside.com 2019 - 2024. All rights reserved.