Javascript 角度http post通过服务将数据返回到组件
我想通过服务将数据(@@identity)从sql server返回到组件 Web api肯定正在被调用并将数据发送回 但是,由于我不熟悉Angular 2/4(我以前习惯Angular 1),我通常只会对服务执行Javascript 角度http post通过服务将数据返回到组件,javascript,angular,typescript,observable,angular-services,Javascript,Angular,Typescript,Observable,Angular Services,我想通过服务将数据(@@identity)从sql server返回到组件 Web api肯定正在被调用并将数据发送回 但是,由于我不熟悉Angular 2/4(我以前习惯Angular 1),我通常只会对服务执行返回,并向调用者设置变量或对象 目前这就是我正在做的 组件 this.trackerFormService.addSession(); // CURRENT this.service.addSession(this.data).subscribe( data =>
返回,并向调用者设置变量或对象
目前这就是我正在做的
组件
this.trackerFormService.addSession(); // CURRENT
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
)
但是,既然值是一个单一的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 this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();
但这真的会起作用吗
Web api(.net core)如下所示
return Created($"api/sessiontrackers/{sessionTracker.Id}", sessionTracker);
您可以从addSession
返回可观察的
,无需。订阅
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);
这肯定会帮助您对web api进行后期调用
为您服务
return this.http.post(Url, JSON.stringify(data), requestOptions)
.map((response: Response) => response.json())
在您的组件中
this.trackerFormService.addSession(); // CURRENT
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
)
我似乎获得了太多的数据,比如对status的响应:201 Create for URL…
如何让组件订阅者正确地执行数据的console.log?