首页 > 解决方案 > 如何在 http.post 之后使用响应数据(来自帖子)重定向到外部 URL

问题描述

this.http.post<any>('https://api.mysite.com/sources', [..body], [...header])
  .subscribe(async res => {
    const someData = res.data;
    const url =  res.url;

    window.location.href = url  
})

这将重定向到指定的 url,但是当重定向发生时如何包含 someData?

标签: javascriptangulartypescriptrest

解决方案


您可以将数据作为查询参数发送

   this.http.post<any>('https://api.mysite.com/sources', [..body], [...header])
      .subscribe(async res => {
         const someData = res.data;
         const url =  res.url;

         window.location.href = url + `?data1=${yourData1}&data2=${yourData2}`
    })

并在到达其他应用程序时接收这些数据

    private readRedirectionData() {
       const url = window.location.toString();
       const data1 = this.getUrlParameter(url, 'data1');
       const data2 = this.getUrlParameter(url, 'data2');
    }

    private getUrlParameter(url, name) {
       if (!url) {
          return '';
       }
       if (!name) {
          return '';
       }
       name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
       const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
       const results = regex.exec(url);
       return results === null ? '' : decodeURIComponent(results[1]);
    }

推荐阅读