【问题标题】:Angular - How to check for pending requests?Angular - 如何检查待处理的请求?
【发布时间】:2018-08-27 14:57:03
【问题描述】:

我的应用中有以下主机组件和一个子组件。

@Component({
  selector: 'ng-host',
  templateUrl: '<div><router-outlet></router-outlet></div>'
})
class HostComponent {
  constructor(
    private ressourceService: RessourceService
  ) {
    this.ressourceService.GetRessource().subscribe();
  }
}

@Component({
  selector: 'ng-child',
  templateUrl: '<div></div>'
})
class ChildComponent {
  constructor(
    private ressourceService: RessourceService
  ) {
    if (this.ressourceService.ressource === null) {
      this.ressourceService.GetOtherRessource().subscribe();
    }
  }
}

它们都为资源注入相同的服务:

@Injectable()
class RessourceService {
  public ressource: any;

  constructor(private http: HttpClient) { }

  GetRessource() {
    return this.http.get('url').pipe(
      map(response => this.ressource = response.ressource)
    );
  }
  GetOtherRessource() {
    return this.http.get('otherUrl');
  }
}

通常用户将登录,登陆主机组件并自然地浏览应用程序,直到他到达子组件。由于主机组件已经实例化,子组件可以检查是否加载了资源,只有在没有加载时才加载其他资源。一切正常。

但是如果我重新加载页面,主机和子组件将同时加载。由于来自宿主组件的请求还在等待中,并且服务的资源还没有设置,子组件将假定该资源不存在并加载另一个资源。

如何防止这种情况发生?有没有办法检查是否有任何请求仍在等待处理?如果在不同的组件中调用它们,是否可以链接这两个请求?还是我需要彻底改变我的应用程序的结构?

【问题讨论】:

  • 听起来你需要一种方法来存储第一个请求的 observable 并将其返回给同时发出请求的任何其他组件。查看stackoverflow.com/questions/45201555/…
  • 您可以在服务中使用 rxjs 的竞赛功能来链接两个查询。您还可以使用拦截器来捕获第二个查询。

标签: angular request rxjs


【解决方案1】:

您可以“缓存”服务中的响应

@Injectable()
class RessourceService {
  public resource1: any;
  public resource2: any;

  constructor(private http: HttpClient) { }

  GetRessource() {
    if (!resource1)
       return this.http.get('url').pipe(
        map(response => response.resource), //not return response, just response.resource
        tap(response=>this.resource1=response)  //when subscribe store the response
    )
     else
        return of(this.resource1)
  }
  GetOtherRessource() {
    if (!resource2)
       return this.http.get('otherurl').pipe(
        map(response => response.resource),
        tap(response=>this.resource2=response)
    )
     else
        return of(this.resource2)
  }
}

然后,您总是订阅 GetResponse 和 GetResponse2

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2021-05-11
    • 1970-01-01
    • 2021-08-16
    • 2016-11-10
    相关资源
    最近更新 更多