[英]rxjs subscription in a service does not fire
I am using the Angular 2 router to split up my app's login page, whilst using an AppComponent
to hold the structuring of routes. 我正在使用Angular 2路由器来拆分应用程序的登录页面,同时使用
AppComponent
来保存路由的结构。 I am also using a UserService
to handle the rxjs subscription. 我还使用
UserService
处理rxjs订阅。
I'm not sure if I am misunderstanding the subscriptions purpose, but the main reason i'm using it is so AppComponent
will know when a user is/not logged in. 我不确定我是否误解了订阅目的,但是我使用它的主要原因是,这样
AppComponent
就会知道用户何时登录。
It seems that only the initial false
I set in new BehaviorSubject<Boolean>(false);
似乎只有
new BehaviorSubject<Boolean>(false);
设置的初始false
new BehaviorSubject<Boolean>(false);
actually gets returned. 实际上得到了回报。 But when I actually run the
login()
function, nothing happens... 但是当我实际运行
login()
函数时,什么也没发生...
https://plnkr.co/edit/J2TtNawZro8AxLqk4JKf?p=preview https://plnkr.co/edit/J2TtNawZro8AxLqk4JKf?p=preview
src/user.service.ts 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 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.component.ts src / login.component.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();
}
}
remove providers: [UserService]
from login and app component 从登录名和应用程序组件中删除
providers: [UserService]
working plunkr is here https://plnkr.co/edit/Y1tHx0nS2KQzS55PqW7L?p=preview 工作的plunkr在这里https://plnkr.co/edit/Y1tHx0nS2KQzS55PqW7L?p=preview
your code is creating multiple instances of UserService
您的代码正在创建
UserService
多个实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.