【问题标题】:New to angular, cant wrap my head around accessing variables from outside of a componentAngular 新手,无法从组件外部访问变量
【发布时间】:2019-05-02 05:02:51
【问题描述】:

好的,让我尽量总结一下。我是 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 的任何其他请求的标头中提交它,但现在我什至无法在它所在组件的 HTML 中访问它

【问题讨论】:

    标签: angular angular6 angular-components angular7


    【解决方案1】:

    您并不真的希望将其作为变量全局访问 - 将其留在服务中并将其注入您想要的位置(正如您已经在做的那样)。这将允许更好的数据封装。

    要在组件 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 }} 不需要更改。

    【讨论】:

    • 你摇滚!!!我完全迷失在公共部分。这非常有效。谢谢!
    • @DanielStockbridge 很高兴我能帮上忙,你已经非常接近了。
    • 不幸的是,“非常接近”让我把头撞在墙上太久了。踢自己不只是尽快启动堆栈溢出帐户并询问
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多