0
我正在使用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();
}
}
多個實例,非常感謝您! –