我目前正在尝试更新map()函数中的全局变量foundProfile
。现在,我有一半意识到这可能不是我应该做的事情 - 但我无法弄清楚原因,也不能想到任何其他方式将变量设置为true如果有&# 39; sa匹配。这是我目前的代码:
export class LoginComponent implements OnInit {
private usernameTxt: string;
private passwordTxt: string;
private foundProfile: boolean;
constructor(private router: Router, private page: Page, private loginService: LoginService, private profileService: ProfileService) {
page.actionBarHidden = true;
}
ngOnInit() {
this.usernameTxt = 'someUsername';
this.passwordTxt = 'SomePassword321!';
this.foundProfile = false;
}
getProfile(username: string, password: string) {
return this.loginService.getProfiles()
.map(
profiles => profiles.filter(
(profile => {
if(profile.email == username && profile.password == password) {
this.foundProfile = true; //Set to true so we know a profile has been found
return profile;
}
})
)
);
}
doLogin() {
if(this.checkValues(this.usernameTxt, this.passwordTxt)) {
this.profileService.profile = this.getProfile(this.usernameTxt, this.passwordTxt);
console.log(this.foundProfile);
}
}
}
现在,我的问题如下:
为什么this.foundProfile = true;
功能中的map()
未将private foundProfile: boolean;
设置为true
?我确定我以错误的方式解决这个问题 - 但为什么会这样呢?我应该做些什么呢?
提前致谢。
编辑: 在我的loginService中,我是这样开始我的观察:
getProfiles(): Observable<Profile[]> {
return this.http.get<Profile[]>(this.url);
}
答案 0 :(得分:0)
如果你想更新你的foundProfile,不要在.map中设置它,如果你想处理它,你需要一个.subscribe()!
另一件事是你试图将一个承诺放到this.profileService.profile中,但你不希望承诺只是解决后的值。
getProfile仅返回地图的优点是,您可以为所需的每个订阅更改/调整过滤器。
// Better to put this function in profile service then call this.profileService.getProfile
getProfile(username: string, password: string) {
return this.loginService.getProfiles()
.map((res: any) => {
return res.json();
});
}
doLogin() {
if(this.checkValues(this.usernameTxt, this.passwordTxt)) {
// removed this.profileService.profile = this.getProfile...
this.getProfile(this.usernameTxt, this.passwordTxt).subscribe(
(profiles) => profiles.filter(
profile => {
if(profile.email == username && profile.password == password) {
this.profileService.profile = true; // update your service value
this.foundProfile = true; //Set to true so we know a profile has been found
return profile;
}
})
)
console.log(this.foundProfile);
}
}