在服务中的rxjs订阅不会触发
问题描述:
我正在使用Angular 2路由器来分割我的应用的登录页面,同时使用AppComponent
来保存路由的结构。我也使用UserService
来处理rxjs订阅。在服务中的rxjs订阅不会触发
我不知道如果我误解订阅目的,但我使用它的主要原因是如此AppComponent
会知道什么时候是/不登录的用户。
似乎只有初始false
我设置在new BehaviorSubject<Boolean>(false);
实际得到返回。但是当我真正运行login()
功能,没有任何反应......
https://plnkr.co/edit/J2TtNawZro8AxLqk4JKf?p=preview
的src/user.service.ts
@Injectable()
export class UserService {
private _loggedInSource = new BehaviorSubject<Boolean>(false);
// Observable navItem stream
loggedIn$ = this._loggedInSource.asObservable();
login() {
this._loggedInSource.next(true);
}
}
的src/app.component.ts
@Component({
selector: 'my-app',
template: `
<div>
<h2>My app</h2>
logged in?: {{status}}
<router-outlet></router-outlet>
</div>
`,
providers: [UserService]
})
export class AppComponent {
subscription: Subscription;
public status: Boolean = false;
constructor(@Inject(UserService) private userService: UserService) {}
ngOnInit() {
this.subscription = this.userService.loggedIn$
.subscribe(item => this.status = item)
}
ngOnDestroy() { this.subscription.unsubscribe(); }
}
src/login.componen t.ts
@Component({
selector: 'login',
template: `
<form (submit)="login()" class="login" #loginForm="ngForm">
<h2>Login</h2>
<input type="email" placeholder="Email" [(ngModel)]="credentials.email" name="email"/>
<input type="password" placeholder="Password" [(ngModel)]="credentials.password" name="password"/>
<button type="submit">submit</button>
</form>
`,
providers: [UserService]
})
export class LoginComponent {
public credentials: Object = { email: "", password: "" };
constructor(
@Inject(UserService) private userService: UserService
) { }
login(): void {
this.userService.login();
}
}
答
从登录和应用程序组件
删除providers: [UserService]
工作plunkr在这里 https://plnkr.co/edit/Y1tHx0nS2KQzS55PqW7L?p=preview
您的代码创建的UserService
多个实例,非常感谢您! –