Angular http post 到 return 数据通过服务返回到组件

Angular http post to return data back through service to component

我想 return 来自 sql 服务器的数据 (@@identity) 通过服务到组件

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

但是,由于我是 Angular 2/4 的新手(我习惯了 angular 1),我通常只对服务执行 return,然后设置一个变量或反对来电者。

目前我正在做的事情

组件

this.trackerFormService.addSession();  // CURRENT

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

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);

您可以 return 来自 addSessionObservable,无需 .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 到您组件中的可观察对象,当它完成调用时,将值分配给您的 myId

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

这肯定会帮助您 post 调用网络 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
    )