Javascript 角分量特性莫名其妙地保留着;“未定义”;在subscribe()中设置后
让我先说一下是的,我正在使用箭头函数来保留“this”的范围(据我所知) 我的组件上有两个属性: IsAdmin(布尔) 当前角色(字符串) 我通过Angular的HttpClient进行api调用,从后端获取用户角色,我有一个回调订阅方法,该方法使用结果更新上述属性 但是,虽然我可以将角色值分配给currentRole,但即使在分配时,另一个属性IsAdmin仍然未定义,并且我通过chrome插件在f12调试器或visual studio代码中没有收到任何错误Javascript 角分量特性莫名其妙地保留着;“未定义”;在subscribe()中设置后,javascript,angular,typescript,angular-components,angular-httpclient,Javascript,Angular,Typescript,Angular Components,Angular Httpclient,让我先说一下是的,我正在使用箭头函数来保留“this”的范围(据我所知) 我的组件上有两个属性: IsAdmin(布尔) 当前角色(字符串) 我通过Angular的HttpClient进行api调用,从后端获取用户角色,我有一个回调订阅方法,该方法使用结果更新上述属性 但是,虽然我可以将角色值分配给currentRole,但即使在分配时,另一个属性IsAdmin仍然未定义,并且我通过chrome插件在f12调试器或visual studio代码中没有收到任何错误 import {
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));
}
}
这到底是怎么回事?我做错了什么 订阅
的问题在于,您使用的是==
(比较)而不是=
(分配)
您正在使用==您没有将此.IsAdmin
分配给结果。包括(“admin”)
正确。我不知道该说什么。我已经研究这个问题好几个小时了,尝试了所有的方法,但不知怎么的,我没有看到。我想这是漫长的一天。
logon-menu.component.ts:37 this.currentRole admin
logon-menu.component.ts:39 this.IsAdmin undefined
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"
},
subscribe(result => {
this.currentRole = result[0];
this.IsAdmin = result.includes("admin");
},