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

4 javascript observable typescript angular-services angular

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

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

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

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

成分

this.trackerFormService.addSession();  // CURRENT
Run Code Online (Sandbox Code Playgroud)

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

this.myId = this.trackerFormService.addSession();    // ???
Run Code Online (Sandbox Code Playgroud)

然后在服务中

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

}
Run Code Online (Sandbox Code Playgroud)

现在,对于上面的内容,将 ID 从服务(addSession() 方法)传递回组件,我不应该这样做吗return

return this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();
Run Code Online (Sandbox Code Playgroud)

但这真的有效吗?

Web api (.net core) 看起来像这样

return Created($"api/sessiontrackers/{sessionTracker.Id}", sessionTracker);
Run Code Online (Sandbox Code Playgroud)

Dhe*_*mar 5

这肯定会帮助您对 Web api 进行 post 调用

https://dheerajroy.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())
Run Code Online (Sandbox Code Playgroud)

在你的组件中

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
    )
Run Code Online (Sandbox Code Playgroud)