【问题标题】:How to get proper API data for angular app?如何为 Angular 应用程序获取正确的 API 数据?
【发布时间】:2019-10-09 12:04:20
【问题描述】:

我用 nodejs、express 和 mongodb 创建了一个 API 服务。当我用邮递员甚至在浏览器上测试它时,它工作正常。但是,当我尝试从 Angular 应用程序中执行相同操作时,它会给出一个奇怪的响应。

这是我从邮递员提出的获取请求:

api服务的角码:

url = 'http://localhost:3000';
getList() {
  return this.http.get(this.url);
}

当我在 app.component.ts 中执行以下操作时

console.log(JSON.stringify(this.taskapi.getList()));

这是我在控制台中看到的:

{"_isScalar":false,"source":{"_isScalar":false,"source":{"_isScalar":false,"source":{"_isScalar":true,"value":{"url":"http://localhost:3000","body":null,"reportProgress":false,"withCredentials":false,"responseType":"json","method":"GET","headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"params":{"updates":null,"cloneFrom":null,"encoder":{},"map":null},"urlWithParams":"http://localhost:3000"}},"operator":{"concurrent":1}},"operator":{}},"operator":{}}

我希望得到与邮递员相同的角度响应。我该怎么做?

【问题讨论】:

    标签: node.js angular rest api express


    【解决方案1】:

    您应该订阅 observable 以获得结果。 Observables 是惰性的,除非你订阅,否则它不会发起调用

        getList() {
          return this.http.get(this.url);
        }
        list:any;
        this.taskapi.getList().subscribe((response)=>{
             this.list = response;
            //here you will get the response
        });
    

    您还可以使用角度 async 管道,它会自动为您订阅和取消订阅

        <div *ngFor='let item of yourObservableList | async'>
    
        </div>
    

    【讨论】:

    • @San 很高兴来到这里!。将此保存为数组意味着,您是否要再次发布到服务器?你能解释一下你在做什么吗?
    • @San 如果您想在 html 中作为数组进行迭代,请查看更新后的答案。您可以将响应数组保存在另一个属性集合中,并且可以在没有异步管道的情况下在 html 中使用。
    • nvm,我搞定了。我只是想将响应保存在局部变量中,以便稍后访问。原来是类型问题。不管怎么说,还是要谢谢你! :)
    【解决方案2】:

    您的 getList() 函数返回 Observable,这就是 this.http.get 返回的内容。

    只需订阅 Observable 并打印响应,如下所示:

    this.taskapi.getList().subscribe(
      res =>
      {
        console.log(res);
      },
      err =>
      {
        /*Error handling*/
      }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 2021-11-27
      • 2017-06-09
      • 2020-02-07
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多