【问题标题】:I cant get the values of a subscribe in angular 9我无法获得 Angular 9 中的订阅值
【发布时间】:2020-07-06 20:54:50
【问题描述】:

我想获取订阅的状态代码和正文。

哇,我不能。好吧,我可以但完全没用,因为我不能回来。

@Injectable()
export class ApiService {

constructor(private _http: HttpClient, 
              private _authHttp: HttpClient,
              public jwtHelper: JwtHelperService,
              private loggedinService: LoggedinService){

  }

  status_code:number

 def test(){
    var result_ = this._http.get(this.getEndpointUrl(endpoint), {headers: new HttpHeaders({ 'Content-Type':  'application/json','Authorization': localStorage.getItem('id_token') }),observe: 'response'});

    result_.subscribe(resp=>{
      this.status_code = resp.status
      console.log(resp.status). //works
    })

    let wtf = result_.toPromise().then(resp => console.log('toPromise', this.status_code = resp.status));

   return this.status_code.  //null

 }

如何等待返回?订阅完成前明确返回

【问题讨论】:

标签: javascript angular typescript http rxjs


【解决方案1】:

订阅是异步完成的,这就是为什么当您同步返回 this.status_code 的值时它没有设置。

你能做的就是返回

this._http.get(this.getEndpointUrl(endpoint), {headers: new HttpHeaders({ 'Content-Type':  'application/json','Authorization': localStorage.getItem('id_token') }),observe: 'response'})

在您的方法中并在调用该方法的地方订阅它。

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2020-07-20
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多