【问题标题】:Get response of POST request in angular 6以角度 6 获取 POST 请求的响应
【发布时间】:2018-08-29 12:32:05
【问题描述】:

我正在使用 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。

【问题讨论】:

  • 我的问题是为什么 newProjectId 是未定义的,即使我可以通过 console.log 在 subscribe 中获取它的值?
  • 因为你是异步设置的

标签: angular typescript httpclient


【解决方案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 自己处理所有事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    相关资源
    最近更新 更多