Angular 2 http.get请求多次执行

时间:2017-03-21 10:36:32

标签: angular rxjs angular2-http angular2-observables

在我的服务中,我有一个从服务器获取一些数据的函数。我的应用程序的几个部分在初始化时调用此函数。而我想要做的是:如果已经有一个请求被发送,另一个请求等待响应(他们不需要自己发出请求)。

所以我的代码是:

@Injectable()
export class UserService implements OnInit {
  ngOnInit(){
        this.getUserInformations();
  };

  public getUserInformations(forceRefresh?: boolean): Observable<Object>{

        if(this.userInformationsLastObservable == null) {
            console.log('Making a request'); // called only once at init
            this.userInformationsLastObservable = this.http.get(this.baseUrl + "informations")
            .map((result: Response) => {
                console.log('map is called'); // called 5 times at init
                let userInformations = result.json();
                /* So future calls will perform a new request */
                this.userInformationsLastObservable = null;
                return userInformations;
            });
        }

        return this.userInformationsLastObservable;
    };
}

有几个组件称之为:

@Component({
  selector: 'app-leaderboard',
  templateUrl: 'leaderboard.component.html',
  styleUrls:  ['leaderboard.component.css'],
  providers: []

})
export class LeaderboardComponent implements OnInit
{
  ngOnInit(){
      this.userService.getUserInformations().subscribe((userInformations) => {
        this.userInformations = userInformations;
        /* this function does not make any call to the User service */
        this.refresh();
      }, () => {
        this.isLoading = false;
      });

    };
}

问题是:从控制台的“网络”面板,我看到在初始时发送了5个请求。并且'地图被呼叫'也被打印5次,而“提出请求”只被调用一次。

我做错了什么?

感谢您的帮助 enter image description here enter image description here

3 个答案:

答案 0 :(得分:1)

发现问题来自于我对rxjs Observable如何工作的误解。我不知道每次你订阅其中一个,它都会重新执行它。 在这里,每次订阅this.userInformationsLastObservable时,它都会再次进行http调用。我认为只能在创建时进行呼叫,然后在收到响应时通知所有用户。

所以我想我会通过使用主题来解决这个问题。

答案 1 :(得分:0)

从另一个请求收到响应后发送的请求应该在组件中服务的订阅方法中注册。

在组件中:

constructor(private _service: Service) { }

ngOnInit() {
  this._service.getUserInformations().subscribe(
    res => {
      // call another service;
    }
}

无论响应数组的长度如何,第二个请求只会发送一次。

答案 2 :(得分:0)

public getConfig(): ReplaySubject<HomeConfig> {

    if (this.replayConfigRequest) {
        return this.replayConfigRequest;
    }

    this.configRequest = this.http.get<HomeConfig>(this.meta.configUrl);

    this.replayConfigRequest = new ReplaySubject<HomeConfig>(1);

    this.configRequest.subscribe(this.replayConfigRequest);

    return this.replayConfigRequest;
}
相关问题