내 서비스에서 서버에서 데이터를 가져 오는 기능이 있습니다. 내 응용 프로그램의 여러 부분에서 초기화시이 함수를 호출합니다. 그리고 내가하고 싶은 것은 : 이미 하나의 요청이 전송되고 있다면, 다른 하나는 응답을 기다린다 (그들은 자신의 요청을 할 필요가 없다).각도 2 http.get 요청이 여러 번 수행되었습니다.
그래서 내 코드는 다음과 같습니다
@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 번 인쇄되는 반면 '요청하기'는 한 번만 호출됩니다.
내가 뭘 잘못하고 있니? 다른 요청에서 응답을받은 후 보내 당신의 도움이
실제로 네트워크 탭에 5 개의 네트워크 요청이 표시됩니까? 스크린 샷을 찍을 수 있습니까? – echonax
예 :) (내 게시물 편집) –
좋아, 이제는 앵귤러 2 서비스가 싱글 톤이 아니라는 사실을 확신 할 수 있습니다 (http://stackoverflow.com/a/36200020/6408940 참조). 약간의 테스트를 할 것입니다 –