Angular 从home.ts页中的component.ts获取令牌值

Angular 从home.ts页中的component.ts获取令牌值,angular,typescript,ionic-framework,Angular,Typescript,Ionic Framework,推送通知的令牌在app.component.ts中生成。我想在home.ts页面中读取生成的token 我已经在app.component.ts和home.ts中创建了user.service.ts,import它 我在app.component.ts中的this.user.token中添加了token的值,如下所示 initializeApp() { this.platform.ready().then(() => { this.statusBar.styleDe

推送通知的令牌在
app.component.ts
中生成。我想在
home.ts
页面中读取生成的
token

我已经在
app.component.ts
home.ts中创建了
user.service.ts
import

我在
app.component.ts
中的
this.user.token
中添加了token的值,如下所示

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      //for android push
      this.fcm.getToken().then(token => {
        console.log(token);
      });

      //Add this function to refresh the FCM token.
      this.fcm.onTokenRefresh().subscribe(token => {
        console.log(token);       // i can see value of token in console
        this.user.token = token;  // passing the value of token here
      });
当I
console.log(this.user.token)时,在
home.ts
,它是空的

ngOnInit(){
console.log(this.user.token);  // I cannot see value of token in home.ts
}
如果我从
app.component.ts
console.log
生成令牌,我可以看到它,但无法将它带到
home.ts


我缺少什么?

您不能直接使用另一个组件的变量,您应该将值保存在服务中,然后您可以在另一个组件中获得它,因为您已经注入了服务

 constructor (private authService: AuthService, private router: Router) {
   console.log(this.authService.user.token);
 }

我希望你的
user.service.ts
有一个名为
token
的属性,将你的服务注入你的
app.component.ts
构造函数,如下所示

constructor(private userService: UserService){}
如您所做,在app.component.ts中

this.fcm.onTokenRefresh().subscribe(token => {
        console.log(token);       // i can see value of token in console
        this.userService.token = token;  // passing the value of token here
      });
现在,如果您在
home.ts
的构造函数中注入userService,您将能够以
this.userService.token

否则

如果令牌是子组件,则可以将其作为输入传递给您的
home.component.ts
。如下



您不能从另一个组件访问变量,因为它是,您需要一个服务当然我有这两个,我发布了我的问题,因为这样做后,它不起作用。您可以发布两个组件的src吗?这将提供关于这个问题的更多细节