angular 的新手,无法全神贯注地从组件外部访问变量

New to angular, cant wrap my head around accessing variables from outside of a component

好吧,我尽量总结一下。我是 Angular 的新手,已经进行了相当彻底的搜索,但似乎找不到我的问题的答案:

现在我有: Api.Service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';


const httpOptions = {
  headers: new HttpHeaders({
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  })
};

@Injectable({ providedIn: 'root' })

export class TokenService {
  private tokenUrl = 'http://urlofapi/auth/token';

  constructor(private http: HttpClient) { }

  addToken(): Observable<any> {
    return this.http.post(this.tokenUrl, httpOptions);
  }

}

api.component.ts

import { Component, OnInit } from '@angular/core';
import { TokenService } from '../api.service';

@Component({
  selector: 'app-api',
  templateUrl: './api.component.html',
  styleUrls: ['./api.component.scss']
})

export class ApiComponent implements OnInit {

  constructor(private tokenService: TokenService) { }

  ngOnInit() {
    this.tokenService.addToken().subscribe((data => {
      this.data = data;
      const finalToken = this.data['token'];

      console.log(finalToken);
    });

  }
}

正在通过 POST 握手从 API 返回令牌。它以以下格式返回:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVVUlEIjoiYTM3YWFmNzAtZjU0Yy00MGMwLWEwZGUtOTE4NTBkNjY1ODI2IiwiZGV2aWNlSWQiOiIxMjIzMzMiLCJleHBpcmVzQXQiOiIyMDE4LTExLTI5VDIwOjI4OjM3WiJ9.VcTt_TJWFA58iBCDS0JnTAJkH9EzU15QES9k0vI84Ic"
}

我正在将令牌记录到控制台,所以我知道它正在定义和接收它。

所以我的问题 我正在获取令牌,它被设置为 finalToken,它被记录到控制台。问题是由于某种原因,该变量对应用程序的任何其他部分都不可见

因此,如果我尝试从 ngOnInit(){} 包装器之外的任何地方调用它,它会返回为未定义。

例如,如果我想在我的 api.component.html 中使用以下命令将其打印到屏幕上:

{{ finalToken }}

在浏览器中,我得到:

<p _ngcontent-c1=""></p>

没有错误,但没有拉取变量

非常tl:dr;是否可以使 const finalToken 在全球范围内可用?我将需要能够在 API 的任何其他请求的 header 中提交它,但现在我什至无法在它所在的组件的 HTML 中访问它

你真的不想让它作为一个变量在全球范围内访问——把它留在服务中,然后将它注入你想要的地方(就像你已经在做的那样)。这将允许更好的数据封装。

要在组件 html 中访问它,您需要为其创建一个 public 属性。所以而不是:

ngOnInit() {
    this.tokenService.addToken().subscribe((data => {
      this.data = data;
      const finalToken = this.data['token'];

      console.log(finalToken);
    });

  }

这样做:

public finalToken: string = null;
ngOnInit() {
    this.tokenService.addToken().subscribe((data => {
      this.data = data;
      this.finalToken = this.data['token'];

      console.log(finalToken);
    });

  }

你的html{{ finalToken }}不需要改变。