我有一个问题是将订阅的值传递给另一个组件。
Structur:
app/
---elements/
------navigation.component.ts
---pages/
------login/
----------login.component.ts
login.component.ts
isAuthenticated: any = false;
onSignin() {
this.authService.signinUser(this.myForm.value)
.subscribe(
data => {
this.isAuthenticated = data;
});
}
如果登录成功,则 this.isAuthenticated
为真。
将 isAuthenticated 的数据发送到 navigation.component.ts 的最佳方法是什么?
navigation.component.ts
isAuthenticated: any = false;
constructor (private authService: AuthService, private router: Router) {
this.authService.isAuthenticated()
.subscribe(data => {
this.isAuthenticated = data;
});
}
添加了: 的 auth.service.ts
isAuthenticated() {
if (this.currentUser != null) {
const token = this.currentUser.token;
const body = JSON.stringify({token: token});
return this.http.post('https://test.com/src/v13n22214', body)
.map((response: Response) => {
const authResponse = response.json().response;
if (authResponse) {
return true;
} else {
return false;
}
});
}
答案 0 :(得分:0)
您应该将值保存在服务中,然后您可以在另一个组件中获取它,因为您已经注入了服务
constructor (private authService: AuthService, private router: Router) {
this.isAuthenticated = this.authService.isAuthenticated();
}