我想创建一个嵌套的 observable 来保存一个与标签相关的内容。首先保存内容并返回内容 id 以保存标签,内容 id 作为外键,顺便说一下,服务在我的循环中同时发送数据。(后端日志运行并行)我怎样才能让它等到完成后再做下一个
组件.ts
save(){
this.contentService.savecontent(this.content_input) // save content
.subscribe(
data => { this.listContentData = data }, // return data to get content id
error => { error = error },
() => {
this.savetag(this.listContentData); // save tag
});
}
savetag(listcontentdata): void {
// listdraftCategories is a list of tag
for (var i = 0; i < this.listdraftCategories.length; i++) {
this.tagService.savetagwithcontent(this.listdraftCategories[i], listcontentdata)
.subscribe(
data => { data = data },
error => { },
() => {
});
}
}
服务.ts
savecontent(contentObj: any): Observable<any> {
contentObj = JSON.parse(contentObj);
let body = JSON.stringify(
{
"token": "test",
"content": {
"contentName": contentObj.itemName // contentId will be autoincrement in backend
}
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.host + this.url_content + this.url_save, body, options)
.map(res => this.extractData(res))
.catch(this.handleError);
}
savetagwithcontent(tagObj: any, contentObj: any): Observable<any> {
console.log("obj", contentObj);
let body = JSON.stringify(
{
"token": "test",
"content": {
"fkTag": {
"tagId": tagObj.tagId
},
"fkContent": {
"contentId": contentObj.responseObject[0].contentId
}
}
}
);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.host + this.url_tag_has_content + this.url_save, body, options)
.map(res => this.extractData(res))
.catch(this.handleError);
}
后端日志(用内容保存标签)
--- start save tag with content ---
--- start save tag with content ---
--- content id : 1 tag id: 1 ---
--- content id : 1 tag id: 2 ---
--- end save tag with content ---
--- end save tag with content ---
看起来它几乎同时进入了方法。我怎样才能设法让 savetag 等待一个保存完成然后再做下一个?