Angular2 ChangeDetection还是可观察的? [英] Angular2 ChangeDetection or Observable?

查看:64
本文介绍了Angular2 ChangeDetection还是可观察的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了无法在登录时刷新的组件的问题.

I'm having difficulty with a component that doesn't refresh upon log in.

该组件是navbar.component,其中包含指向我的页面/组件的链接.在其上,有一个"login"链接,呈现了login.component,可以在其上提供用户名和密码,然后单击登录"按钮. login.component使用user.service,后者使用login.component提供的用户名和密码来调用后端,存储接收到的令牌并重定向到"/".

The component is navbar.component that contains links to my pages/components. On it, there is a "login" link that renders login.component on which I can provide username and password and click the login button. login.component uses user.service which calls the backend with the username and password provided by login.component, stores the received token and redirects to '/'.

这时,应该隐藏navbar.component上的登录"链接,并显示退出"链接,但是在单击导航条上的其他链接之一之前,什么也没有发生.

At this point, the "login" link on navbar.component should be hidden and the "logout" link shown, but nothing happens until I click one of the other links on the navbar.

2个链接如下:

<a [hidden]="userService.isLoggedIn" [routerLink]="['Login']">Login</a>
<a [hidden]="!userService.isLoggedIn" (click)="userService.logout();" href="javascript:void(0)">Logout</a>

我了解到存储令牌并从user.service重定向不会触发更改检测,并且我的属性userService.isLoggedIn不是可观察到的,所以我知道我丢失了一些内容,但不确定该采用哪种方法/应该是.

I understand storing the token and redirecting from user.service doesn't trigger change detection, and that my property userService.isLoggedIn isn't an observable, so I know I'm missing something, but not sure what the approach is/should be.

我尝试注入ApplicationRef来调用tick()方法,希望这会触发更改检测,但失败了.

I have tried injecting ApplicationRef to call the tick() method hoping this would trigger change detection, but failed.

我应该使我的属性userService.isLoggedIn可见吗?

Should I make my property userService.isLoggedIn an observable?

推荐答案

export class UserService {
  isLoggedIn:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}

@Component({
...
template: `
<a [hidden]="userService.isLoggedIn | async" [routerLink]="['Login']">Login</a>
<a [hidden]="!(userService.isLoggedIn | async)" (click)="userService.logout();" href="javascript:void(0)">Logout</a>
`

})
export class MyComponent {
  constructor(private userService: UserService) {}
}

这篇关于Angular2 ChangeDetection还是可观察的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆