我无法在角度9中获得订阅的值

时间:2020-03-26 08:48:25

标签: javascript angular typescript http rxjs

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

哇,我不能。好吧,因为我无法返回,我只能但毫无用处。

@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

 }

我如何等待返回?在订阅完成之前显然会返回

1 个答案:

答案 0 :(得分:2)

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

你能做的就是回来

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

在您的方法中,并在调用该方法的位置进行订阅。