未捕获(承诺):TypeError:无法读取未定义的属性“ userSubject” TypeError:无法读取未定义的属性“ userSubject”

时间:2020-05-03 12:04:35

标签: javascript angular promise rxjs

我想打电话

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

1 个答案:

答案 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;
  });
}