我想打电话
login(username, password) {
return Parse.User.logIn(username, password)
.then(function (user) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
console.log(user);
this.userSubject.next(user);
return user;
});
}
像这样
login(username, password) {
return this.http.post<user>(`${environment.apiUrl}/users/authenticate`, { username, password })
.pipe(map(user => {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
console.log(user);
this.userSubject.next(user);
return user;
}));
}
但这会导致错误
Uncaught (in promise): TypeError: Cannot read property 'userSubject' of undefined
TypeError: Cannot read property 'userSubject' of undefined
答案 0 :(得分:0)
问题是您使用普通函数而不是箭头函数。
普通函数具有自己的this
指针。
只需使用箭头功能即可。
login(username, password) {
return Parse.User.logIn(username, password)
.then((user) => { // <-- here is the change
localStorage.setItem('user', JSON.stringify(user));
console.log(user);
this.userSubject.next(user);
return user;
});
}