【问题标题】:Angular 2 consecutive http requestsAngular 2个连续的http请求
【发布时间】:2018-02-13 06:59:24
【问题描述】:

在我的角度数据服务中,我尝试发出两个 http 请求,第二个请求取决于第一个请求中的数据。第一个请求工作正常,但由于某种原因,第二个请求永远不会到达我的后端服务器。我希望有人能告诉我我这样做是否正确或告诉我我做错了什么。

@Injectable()
export class DataService {

  constructor( private http: Http ) { }

public twoRequest() {
    this.http.get(`http://localhost:3000/1st_request`).subscribe((data) => 
      this.http.post(`http://localhost:3000/2nd_request`, {data: data}))
}

编辑:我没有订阅第二个请求。我不知道你必须订阅你提出的每个请求,即使它们在同一个代码块中

【问题讨论】:

  • 它有点不同,因为我在同一个块中进行了两次调用。我认为这个问题将来对其他人有用。

标签: angular typescript observable angular-http angular-observable


【解决方案1】:

您还需要将subscribe 发送到http.post。如果你不subscribe 给它,它永远不会发出请求。

@Injectable()
export class DataService {

  constructor( private http: Http ) { }

  public twoRequest() {
     this.http.get(`http://localhost:3000/1st_request`).subscribe((data) => 
       this.http.post(`http://localhost:3000/2nd_request`, {data: data}).subscribe(/*...*/));
}

【讨论】:

    【解决方案2】:
    public twoRequest() {
            this.http.get(`http://localhost:3000/1st_request`).subscribe((data) => {
                this.http.post(`http://localhost:3000/2nd_request`, {data:data})) 
                   .subscribe((resp: any) => {
                     console.log(resp)
                 })
               }
    
        }
    

    【讨论】:

    • 不依赖花括号,他没有订阅第二个帖子。 @suren 正确指出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2018-01-28
    • 2017-11-29
    • 1970-01-01
    相关资源
    最近更新 更多