【问题标题】:How could I send the token returned from a post request in a get request in Angular如何在 Angular 的 get 请求中发送从 post 请求返回的令牌
【发布时间】:2019-06-06 03:03:06
【问题描述】:

我需要发送一个我在发布请求中收到的令牌。我必须在 get 请求中发送令牌,我正在做的是将 post 请求返回的令牌保存在一个中,请注意在GetToken 我将其发送到控制台显示,如果显示,即,如果它正在执行分配,但是当我尝试从ObternerInmueble() 打印它时它打印为空,我不知道为什么?

这是我的代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Inmueble } from '../modelos/inmueble';

@Injectable({
  providedIn: 'root'
})
export class HostlistService {
  cabecera = {
    'Accept': 'application/json',
    'Authorization': ""
  }

  parametros = {
    'grant_type':'client_credentials',
    'client_id': 1,
    'client_secret': 'clientSecret'
  }

  constructor(public http: HttpClient) {
  }

  obtenerToken(){
    return this.http.post<any>('URL',this.parametros).subscribe(
      result => {
        this.cabecera.Authorization=result.token_type+" "+result.access_token;
        console.log(this.cabecera.Authorization);  //here I can see that the value is being allocated
        this.obtenerInmuebles().subscribe();

      },error =>{
        console.log(error);
      }
    );
  }

  obtenerInmuebles() {
    console.log("Authorization-----------_>"+this.cabecera.Authorization);
    return this.http.get<any>('URL',{ headers: new HttpHeaders(this.cabecera) 
    });
  }

  mostrarCabecera(){
    console.log("CABECERA::::::::"+this.cabecera.Authorization);
  }
}

这是他调用方法的地方:

import { Component, OnInit } from '@angular/core';
import { HostlistService } from '../servicios/hostlist.service';
import {$,jQuery} from 'jquery';
import { Inmueble } from '../modelos/inmueble';

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

export class SliderComponent implements OnInit {
  inmuebles: Inmueble[] = [];
  i: number=0;

  url: string = "http://crm.seaconfiable.com/upload/";

  constructor(private hostlistService: HostlistService) { }
  ngOnInit() {
    this.hostlistService.obtenerToken();
    this.hostlistService.obtenerInmuebles().subscribe(
      result => {
        console.log("INMUEBLES",result.data);
      },error =>{
        console.log(error);
      }
    );
  }
}

这是浏览器控制台的图像,您可以在其中看到 Authorization 标头被发送为空(空白):

【问题讨论】:

  • 尝试在 obtenerInmuebles() 方法中将返回类型设置为 observable 然后订阅它

标签: angular post get token


【解决方案1】:

问题出在以下几行 -

this.hostlistService.obtenerToken();
this.hostlistService.obtenerInmuebles().subscribe

this.hostlistService.obtenerToken() 方法在您订阅时发出 HTTP 调用,而在等待响应时 [由于 JS 的异步性质],另一行被执行 this.hostlistService.obtenerInmuebles().subscribe。

你必须等待 this.hostlistService.obtenerToken() observable 的响应。为此,您应该使用管道函数(请参阅https://rxjs-dev.firebaseapp.com/guide/operators 的“管道”主题)并链接各种运算符(根据您的需要)来使用可观察链接。

您可以执行以下操作 -

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Inmueble } from '../modelos/inmueble';

@Injectable({
  providedIn: 'root'
})
export class HostlistService {

    cabecera = {
      'Accept': 'application/json',
      'Authorization': ""
    }

    parametros = {
      'grant_type':'client_credentials',
      'client_id': 1,
      'client_secret': 'clientSecret'
    }


  constructor(public http: HttpClient) {

  }


  obtenerToken(){
    return this.http.post<any>('URL',this.parametros);    
  }


  obtenerInmuebles(resultToken){
    console.log("Authorization-----------_>"+this.cabecera.Authorization);
    this.cabecera.Authorization=resultToken.token_type+" "+resultToken.access_token;
    return this.http.get<any>('URL',{ headers: new HttpHeaders(this.cabecera) });
  }

  mostrarCabecera(){
    console.log("CABECERA::::::::"+this.cabecera.Authorization);
  }

}

import { Component, OnInit } from '@angular/core';
import { HostlistService } from '../servicios/hostlist.service';
import {$,jQuery} from 'jquery';
import { Inmueble } from '../modelos/inmueble';

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

export class SliderComponent implements OnInit {
  inmuebles: Inmueble[] = [];
  i: number=0;

  url: string = "http://crm.seaconfiable.com/upload/";

  constructor(private hostlistService: HostlistService) { }
  ngOnInit() {

    this.hostlistService.obtenerToken()
        .pipe(
          mergeMap(resultToken => this.hostlistService.obtenerInmuebles(resultToken))
        )
        .subscribe(
          result => {
            console.log("INMUEBLES",result.data);
          },error =>{
            console.log(error);
          }
        );    
  }
}

我只修改了您的代码。尽管可能有更好的方法来做同样的事情。希望这会有所帮助。

在上面的代码中,我在 this.hostlistService.obtenerToken() 上使用了管道函数并应用了 mergeMap 运算符,这将确保一旦 this.hostlistService.obtenerToken() 的响应调用 this.hostlistService.obtenerInmuebles(resultToken)) 即可观察) 已收到,这就是我们想要的。

我强烈建议您查看以下网站以了解有关 rxjs 和各种运算符的更多信息 -

https://rxjs-dev.firebaseapp.com/guide/overview https://www.learnrxjs.io/

此外,您可以通过使用异步管道避免显式调用 subscribe()。请参阅以下内容 - https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0

编辑 2 [此编辑是为了展示如何在 localStorage 中保存令牌 [根据用户的要求] -

ngOnInit() {

    this.hostlistService.obtenerToken()
        .pipe(
          mergeMap(resultToken => {
            //do whatever you want to do with the token
            //i.e. Save the token in the localstorage like this - 
            localStorage.setItem("token",resultToken);
            return this.hostlistService.obtenerInmuebles(resultToken);
          })
        )
        .subscribe(
          result => {
            console.log("INMUEBLES",result.data);
          },error =>{
            console.log(error);
          }
        );    
  }

【讨论】:

  • hello @ user2216584 我处理了你的代码,但最近从 Angula 开始,你能解释一下你做了什么吗?特别是关于“pipe”和“mergeMap”?
  • 朋友,我该怎么做才能将 resultToken 保存在本地存储中?我正在尝试这个: this.hostlistService.obtenerToken() .pipe( mergeMap(resultToken => this.hostlistService.obtenerInmuebles(resultToken), localStorage.setItem("token",resultToken)) ) ,朋友我该怎么做才能保存本地存储中的resultToken?我正在尝试这个: this.hostlistService.getToken () .pipe ( mergeMap (resultToken => this.hostlistService.getInput (resultToken), localStorage.setItem ("token", resultToken)) ) 但它不起作用。跨度>
  • @JulianProg 要保存令牌,您只需在返回新的 observable 之前调用 localStorage.setItem("token",resultToken)。请参阅我上面的答案中的“编辑 2”。
  • 非常感谢您的朋友,将您的答案标记为解决方案。很抱歉问了这么多问题,我从 Angular 开始,即使我阅读了文档并寻找示例,我也很难理解。现在我正在尝试使用组件之间的绑定将真实属性传递给另一个组件的模板并从模板打印它,我有很多疑问。如果不是太麻烦,您能不能给我一个可以联系您的社交网络?
  • @JulianProg 非常欢迎您!可以问尽可能多的问题。这就是这个社区的目的..:) 对于任何人来说,任何新事物都有一个学习曲线,并且有问题是探索新事物的正确方法..:) 所以请继续提问..:) 所有社区成员也都会学到新的东西每当其他社区成员提出问题时..:) 我很乐意随时为您提供帮助。只是我不想在公共平台上分享我的社交平台详细信息。如果您能提出一些联系方式,我一定会联系您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
相关资源
最近更新 更多