dragon012100 2018-05-21 12:40
浏览 162
已采纳

Observable不返回api响应

I am new in angular. My Project is in angular5 and I am using a web API created in PHP. My WebApi gives response in postman but not from angular. I am using HttpClient to post request

    export class GalleryComponent implements OnInit {
      private apiUrl = 'http://localhost:8080/fullpath';
      private response;
      private data=[];

      constructor(private http: HttpClient) {
        this.response =this.getCategory();
      }

      getCategory (): Observable<any> {
        return this.http.post(this.apiUrl,{});
      }

      ngOnInit() {
       console.log(this.response);
      }
  }

My console Returns enter image description here

What I have to do to get proper response from API?

  • 写回答

4条回答 默认 最新

  • douhuiyan2772 2018-05-21 12:56
    关注

    When using Observables, you have to subscribe to them. The actual user of the observable needs to subscribe(), because without subscribe() the observable won't be executed at all.

    subscribe() returns a Subscription that can not be subscribed to, but it can be used to cancel the subscription.

     getCategory (): Observable<any> {
          return this.http.post(this.apiUrl,{}).subscribe(
             //Do whatever
            (res)=> console.log(res), 
            (error)=> console.log(error)
          );
        }
    

    For more information you can go to the Angular documentation for Observables: https://angular.io/guide/observables.

    Also, remember that most of the subscriptions terminate by themselves, but is always good practice to terminate them using ngOnDestroy(); to avoid memory leaks.

    How to use ngDestroy()? In you component.ts file Make sure you have the import

    import { Component, OnDestroy, OnInit } from '@angular/core';
    export class YourComponent implements OnInit, OnDestroy {
     .
     .
     .
     ngOnDestroy() {
       this.response.unsubscribe();
      }
    }
    

    Now, related to your CORS Problem, reference the question that has been asked on stackoverflow before: Response to preflight request doesn't pass access control check

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名