服务中的rxjs订阅不会触发

时间:2016-11-29 14:10:45

标签: angular

我正在使用Angular 2路由器拆分我的应用程序的登录页面,同时使用AppComponent来保存路由的结构。我也使用UserService来处理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.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();
    }
}

1 个答案:

答案 0 :(得分:2)

从登录和应用组件中删除providers: [UserService]

工作的plunkr在这里 https://plnkr.co/edit/Y1tHx0nS2KQzS55PqW7L?p=preview

您的代码正在创建UserService

的多个实例