【问题标题】:Working with Observables and Subjects when doing http requests在进行 http 请求时使用 Observables 和 Subjects
【发布时间】:2020-09-18 10:56:05
【问题描述】:

我有一个更大的 Angular 应用程序,我经常需要联系我的后端。大多数时候,我的组件要求相同的对象(或资源)。例如,我有一个包含多个 ChildComponents 的 ParentComponent。在那里,我可以轻松地将我从 ParentComponent.ts 文件中获得的数据通过 @Input 和属性绑定传递给 Children。到现在为止还挺好。但是,如果我有不相关的组件,那么尽可能减少请求以使每个组件都从后端获取对象请求的最佳做法是什么?我知道我必须使用我所做的服务,但现在很多不相关的组件调用相同的 http 方法,因此使用相同的数据。这可以通过使用我猜想的主题来防止,在我在服务中订阅它之后,然后 .next(data) 可能。但后来我不知道哪个组件应该进行实际的 http 调用。感谢您的帮助!

【问题讨论】:

    标签: angular typescript angular2-observables behaviorsubject


    【解决方案1】:

    只需shareReplay 从服务器获取的数据

    class MyService {
       data$ = http.get('url.with.data').pipe(shareReplay(1));
    }
    
    class MyComponent {
    ...
      data$ = this.myService.data$;
    }
    

    这样,结果将被第一个使用该数据的组件懒惰地询问,并且它将在所有组件之间共享

    【讨论】:

      【解决方案2】:

      所有服务都是单例的,因此您可以: 您需要调用该服务,但如果该服务在过去被调用过一次,您只会获得该保存的值,而不会再次调用 http 来获取新值。

      @Injectable({
          providedIn: 'root'
      })
      
      export class YourService {
         data; //persistent data
         //mybe you can implement some algorithm to check the time, and if I spend more than "x" 
         time, force it to call and not just check if I have valid data
         getData() {
             if (!this.data) {
                 http.get('url.com').subscribe((data)=>{
                    this.data = data; 
                    return data;
                 });
             } else {
                 return of(this.data); //of return a observable with the existint data
             }
          }
      }
      

      在每个组件中:

       @Component({
        selector:'',
        template:''}
      );
      export class SomeComponent{
      
      data;
      
      constructor(private yourServices: YourService) { }
      
          chekData() {
              this.yourServices.getData().subscribe(data=>{
              this.data = data;
              });
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-10
        • 2017-03-24
        • 2017-09-09
        • 2016-12-27
        相关资源
        最近更新 更多