我当前正在尝试在map((函数中更新全局变量foundProfile
。现在,我一半意识到这可能不是我应该做事的方式 - 但是我无法找出原因,如果有匹配,我也无法想到其他方法将变量设置为True。这是我当前的代码:
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);
}
}
}
现在,我的问题如下:
为什么map()
内部的this.foundProfile = true;
不将private foundProfile: boolean;
设置为true
?我敢肯定,我要以错误的方式进行操作 - 但是为什么是这样,我应该做什么?
预先感谢。
编辑:在我的loginservice中,我正在启动我的观察力:
getProfiles(): Observable<Profile[]> {
return this.http.get<Profile[]>(this.url);
}
如果要更新您的undprofile,请不要将其设置为.map如果要处理此操作,则需要一个.subscribe((!
另一件事是您尝试在此诺言中承诺。
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);
}
}