【问题标题】:Angular typescript handling post request dataAngular 打字稿处理发布请求数据
【发布时间】:2021-09-03 07:03:59
【问题描述】:

我在组件 TS 文件中创建了一个基本函数,用于发出从服务器检索数据的发布请求。此函数工作正常,但是当我尝试将数据数组放入变量中以便我可以通过 HTML 将其写入页面时,我似乎无法获得预期的效果。好像我做错了什么导致数据没有写入“json”变量。

这是我的组件 TS,我试图将数据传递给的变量是 'json';

  postData = {
    command: 'get_feature',
    classes: 'F,G',
  }
  
  url = "http://c****************"

  json;

  constructor(private http: HttpClient) {
    this.http.post(this.url, this.postData).toPromise().then((data:any) => {
      console.log("post request in progress")
      console.log("printing data array")
      console.log(data)
      this.json = data.json
      console.log("printing json variable")
      console.log(this.json)
      console.log("post request finished")
    });
  }

这里是基本的 HTML,它应该只写数据的类型,因为我还没有对数据进行字符串化,但它完全没有写任何东西,就好像变量中没有任何东西一样。

<pre>
  JSON test

  {{ json }}
</pre>

【问题讨论】:

    标签: html json angular typescript


    【解决方案1】:

    正确的用法是

     // post is generic, so you can pass type here, if no type - pass any
     this.http.post<ResponseType>(this.url, this.postData).toPromise().then((data) => {
          this.json = data
        });
    

    你不能只在mteplate中渲染巨大的json,但你可以尝试json管道,看看那个json里面是什么

    <pre>
      JSON test
    
      {{ json | json }}
    </pre>
    

    【讨论】:

    • 感谢您的建议,不幸的是,这似乎没有任何区别 :( 当我尝试打印“json”变量时,我在控制台中也没有得到任何东西,但它对数据有用吗?
    • 您是否正确复制了this.json = data; 字符串?我尝试使用相同的 api,看来这段代码应该可以工作
    猜你喜欢
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多