简体   繁体   English

可观察的订阅方法仅被调用一次

[英]Observable subscribe method only getting called once

I'm building a simple angular application in which I want a service to hold some state. 我正在构建一个简单的角度应用程序,在该应用程序中我希望服务保持某种状态。 My first attempt at this was just a boolean loggedIn. 我的第一次尝试只是一个布尔值loginIn。 Basically, I want a navbar component to subscribe to this value so that when its false it shows a 'login' option and when its true show an 'admin' button. 基本上,我希望导航栏组件订阅此值,以便当其值为false时显示“登录”选项,而当其值为true时显示“管理”按钮。

My service: 我的服务:

@Injectable()
export class AuthService {
  private _loggedIn = new BehaviorSubject(false);
  public readonly loggedIn$ = this._loggedIn.asObservable();

  constructor(private http: Http, private router: Router) { 
    this._loggedIn = new BehaviorSubject(false);
  }

  public login(u: User): Observable<any> {
    let obs = this.http.post(ApiRoutes.login, u).map(res => res.json());

    obs.subscribe(res => {
      this._loggedIn.next(res.success);

      if (this._loggedIn.getValue())
        this.router.navigate(['/admin']);
    });

    return obs;
  }
}

In my nav component: 在我的导航组件中:

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss'],
  providers: [AuthService]
})
export class NavComponent implements OnInit {
  loggedIn: boolean;

  constructor(private as: AuthService) { }

  ngOnInit() {
    this.as.loggedIn$.subscribe(isLoggedIn => {
      this.loggedIn = isLoggedIn;
      console.log('from nav ' + isLoggedIn);
    }, err => {
      console.log(err);
    }, () => {
      console.log('complete');
    });
  }

}

Right now I see console output when the app starts up but not after login returns. 现在,当应用启动时,但在登录返回后,我没有看到控制台输出。 Why does the subscribe function in the nav component only get called once (the page does navigate to /admin so I know the subscribe in the service is being called)? 为什么导航组件中的订阅功能仅被调用一次(页面确实导航到/ admin,所以我知道服务中的订阅被调用了)? Does this have to do with hot/cold observables? 这与热/冷观测物有关吗? I've tried using things like .publishLast().refCount() but to no avail. 我试过使用.publishLast()。refCount()之类的方法,但无济于事。

You added the AuthService in the providers of the NavComponent. 您在NavComponent的提供程序中添加了AuthService。 So it has its own, specific instance of AuthService, different from the one used by your authentication component. 因此,它具有自己的AuthService特定实例,与身份验证组件所使用的实例不同。

This service must be a singleton, shared by all the components in the application. 该服务必须是单例,由应用程序中的所有组件共享。 So it should be declared in the providers of the root NgModule, and nowhere else. 因此,应该在根NgModule的提供程序中声明它,而在其他地方没有声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM