【问题标题】:Angular http post to return data back through service to componentAngular http post通过服务将数据返回到组件
【发布时间】:2018-02-20 13:03:56
【问题描述】:

我想通过服务从sql server返回数据(@@identity)到组件

Web api 肯定被调用并发送回数据。

但是,由于我是 Angular 2/4 的新手(我习惯于 Angular 1),我通常只会在服务上执行return,然后为调用者设置一个变量或对象。

目前这就是我正在做的事情

组件

this.trackerFormService.addSession();  // CURRENT

但是由于该值是单个 id,例如 5,我不应该在 typescript 中创建一些东西来检索它吗?

this.myId = this.trackerFormService.addSession();    // ???

然后在服务中

private _url = 'http://localhost:60696/api/tracker';

addSession() { 
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();

}

现在将 ID 从服务 (addSession() 方法传回组件,我不应该做一个 return 吗?

return this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();

但这真的会奏效吗?

Web api (.net core) 是这样的

return Created($"api/sessiontrackers/{sessionTracker.Id}", sessionTracker);

【问题讨论】:

    标签: javascript angular typescript observable angular-services


    【解决方案1】:

    这肯定会帮助您对 web api 进行后期调用

    https://dheerajsroy.wixsite.com/dheerajkumar/single-post/2017/09/07/How-to-make-Post-Call-in-Angular-2

    为您服务

     return this.http.post(Url, JSON.stringify(data), requestOptions)
                  .map((response: Response) => response.json())
    

    在您的组件中

    this.service.addSession(this.data).subscribe(
          data => { console.log(data) // Data which is returned by call
          },
          error => { console.log(error); // Error if any
          },
          ()=> // Here call is completed. If you wish to do something 
          // after call is completed(since this is an asynchronous call), this is the right place to do. ex: call another function
        )
    

    【讨论】:

      【解决方案2】:

      您可以从您的addSession 返回Observable,而不使用.subscribe

      addSession() { 
          let headers = new Headers({ 'Content-Type': 'application/json' });
          let options = new RequestOptions({ headers: headers });
      
          return this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError);
      }
      

      因为这是一个异步调用,所以 subscribe 到您的组件中的 observable,当它完成调用时,将值分配给您的 myId

      this.trackerFormService.addSession().subscribe(result => this.myId = result);
      

      【讨论】:

      • 我似乎得到了太多的数据,比如Response with stataus: 201 Create for URL ... 我怎样才能让组件订阅者正确地做一个console.log 的数据?
      猜你喜欢
      • 1970-01-01
      • 2017-07-24
      • 2018-08-03
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多