我正在使用angular来制作与API REST通信的用户界面。 在波纹管功能中,我首先通过发布请求添加项目,然后在表单中添加用户输入的别名列表,然后将别名添加到项目中,然后获取所选应用程序的列表,然后寻找然后将其ID添加到项目中。在帖子下方调用:
addProject(name: string, description: string): void {
// Ajouter un nouveau projet
let newProjectId: number;
let newAliasId: number;
let url = this.baseUrl + "/projects";
this.httpClient.post<Project>(url,
{'name': name, 'description': description },
httpOptions).subscribe((data: any) => { newProjectId = data['result']['id'];})
// Ajouter les alias
for (let entry of this.aliasList) {
let UrlAddAlias = this.baseUrl + "/alias";
this.httpClient.post(UrlAddAlias, {'alias': entry }, httpOptions)
.subscribe((data: any) => { newAliasId = data['result']['id'];});
// Ajouter les alias au nouveau projet
let UrlAliasToProject = this.baseUrl + `/projects/${newProjectId}/alias`;
this.httpClient.post(UrlAliasToProject, {"alias_id" : newAliasId}, httpOptions)
.subscribe((data: any) => { console.log("alias added to project");});
};
// Ajouter les applications selectionnées au nouveau projet
for (let entry of this.selectedApps) {
let Urlapp = this.baseUrl + `/apps/name/${entry}`;
let appId;
this.httpClient.get(Urlapp).subscribe(data => { appId = data['result']['id']; });
let urlappToProject = this.baseUrl + `/projects/${newProjectId}/apps`;
this.httpClient.post(urlappToProject, {'app_id': appId });
};
}
问题是我无法获取newProjectId值和newAliasId值。我收到此错误:
Object { headers: {…}, status: 405, statusText: "Method Not Allowed", url: "http://api.com/v1/projects/undefined/alias", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://api.com/v1/projects/undefined/alias: 405 Method Not Allowed", error: "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n" }
我可以通过console.log
获取值,但它们在其他地方为undefined
。
答案 0 :(得分:1)
.subscribe
回调异步发生。这意味着在其之后编写的代码仍将在其之前执行...类似于setTimeout
setTimeout(() => console.log('second'));
console.log('first');
基本上,您可以将所有内容放在.subscribe
内的.subscribe
之后:
.subscribe((data: any) => {
newProjectId = data['result']['id'];
for (let entry of this.aliasList) { ...
});
如果可能,您可能还希望重新设计API,以不必发出多个请求并让post
自己处理所有事情。