代码之家  ›  专栏  ›  技术社区  ›  Souad Guo Xiuhao

获取6中POST请求的响应

  •  1
  • Souad Guo Xiuhao  · 技术社区  · 6 年前

    我使用angular来创建一个与API REST通信的用户界面。 在下面的函数中,我首先通过post请求添加一个项目,然后在表单中添加用户输入的别名列表,然后将别名添加到项目中,然后获取所选应用程序的列表,查找它们的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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Explosion Pills    6 年前

    .subscribe 回调是异步进行的。这意味着在它之后编写的代码仍将在它之前执行。。。类似 setTimeout

    setTimeout(() => console.log('second'));
    console.log('first');
    

    。订阅 内部 :

    .subscribe((data: any) => {
      newProjectId = data['result']['id'];
    
      for (let entry of this.aliasList) { ...
    });
    

    如果可能的话,您可能还需要重新编写API,这样就不必发出多个请求,并且 post 自己处理一切。