代码之家  ›  专栏  ›  技术社区  ›  user6321478

角度http post通过服务将数据返回到组件

  •  4
  • user6321478  · 技术社区  · 7 年前

    我想通过服务将数据(@@identity)从sql server返回到组件

    Web api肯定正在被调用并将数据发送回。

    然而,由于我不熟悉角度2/4(我以前习惯角度1),我通常只会这样做 return

    目前这就是我正在做的

    this.trackerFormService.addSession();  // CURRENT
    

    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);
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Dheeraj Kumar    7 年前

    这肯定会帮助您对web api进行后期调用

    https://dheerajsroy.wixsite.com/dheerajkumar/single-post/2017/09/07/How-to-make-Post-Call-in-Angular-2

    为您服务

     return this.http.post(Url, JSON.stringify(data), requestOptions)
                  .map((response: Response) => response.json())
    

    在您的组件中

    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
        )
    
        2
  •  2
  •   Suren Srapyan    7 年前

    Observable 从您的 addSession 没有 .subscribe

    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);