订阅主题不会触发

时间:2018-03-14 10:20:39

标签: angular

我正在努力让一个订阅工作没有任何结果。

我的想法是拥有一个订阅AuthService的简单RoutingService,因为我希望路由/导航在AuthService之外发生。当AuthService(登录/注销)发生更改时,我想将事件发送到RoutingService,并根据结果导航到组件。

在添加代码之前,我一直在对其他帖子进行一些研究。以下是您现在想到的问题的一些答案:

  • 我的所有服务仅在我的根模块中声明一次,因此它们是单身。我没有任何其他服务/模块与提供商的元素
  • 我尝试使用Subject,ReplaySubject和BheaviourSubject,结果相同......

找到以下代码:

AuthService类

@Injectable() export class AuthService implements OnInit {

    private authorized = false;
    private googleResponse: GoogleUser;
    authorizationChanges: BehaviorSubject<boolean>;
    authorizationChangesObservable;

    constructor(private router: Router, private googleAuth: GoogleAuthService, private ngZone: NgZone) {
        this.authorizationChanges = new BehaviorSubject<boolean>(this.authorized);
        this.authorizationChangesObservable = this.authorizationChanges.asObservable();
    }

    ngOnInit(): void {
        // also tried to initialize the subject and observable here, same result   }

      //method triggered after a successful signIn   
    private signInSuccessHandler(res: GoogleUser) {
        this.googleResponse = res;
        if (this.validateAccountDomain()) {
            this.authorized = res.isSignedIn();
        }
        console.log('triggering authorizationChanges event');  //<-- I can see this log message in the console
        // So far this is not working
        this.authorizationChanges.next(this.authorized);
    }
}

RoutingService

@Injectable()
export class RoutingService implements OnInit, OnDestroy {
    authorizationUpdates: Subscription;
    constructor(private authService: AuthService, private router: Router) { //tried to subscribe in the constructor, same result
    }
    ngOnInit(): void {
        this.authorizationUpdates = this.authService.authorizationChangesObservable.subscribe((authorized) => {
            console.log(authorized); // <--- I can not see in the console
            this.router.navigate(['assessment'])
        })

     // doesn't work
     // this.authService.authorizationChanges.subscribe(
     //   (authorized) => { console.log('second try')})
    }

    ngOnDestroy(): void {
        this.authorizationUpdates.unsubscribe();
    }
}

1 个答案:

答案 0 :(得分:1)

Lifecycle hooks,与OnInit()一起使用指令和组件。它们不适用于其他类型,例如您的服务中的服务。

OnInit与绑定有关。您希望等待输入值被解析时使用它,因为它们在构造函数中不可用。构造函数可以多次调用。例如,当您更改路线并加载不同的组件时,他们会构建&#34;构建&#34;

每次都被销毁

您可以将ngOnInit逻辑移动到Injectable类的构造函数。