반응형
Angular 2 이상 변수 업데이트/액세스가 완료될 때까지 구독 대기
변수가 정의되지 않은 것에 문제가 있습니다.저는 이것이 관찰 가능한 것이 끝나지 않았기 때문이라고 확신합니다..ts 파일에 있는 제 코드 중 문제를 일으키는 부분이 여기 있습니다.(이 문제를 이해하는 데 필요한 최소 코드를 입력합니다.또한.myFunctionHTML의 클릭 이벤트에서 호출됩니다.
export class myClass {
myVariable: any;
myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
});
console.log(myVariable) --> undefined
}
}
그래서 이 코드 조각은 API에서 일부 데이터를 반환하는 제 서비스의 함수를 호출합니다.문제는 제가 그 변수에 접근하려고 할 때myVariable구독 함수의 바로 바깥쪽에서 정의되지 않은 값을 반환합니다.액세스를 시도하기 전에 구독이 완료되지 않았기 때문이라고 확신합니다.myVariable
액세스를 시도하기 전에 구독이 완료될 때까지 기다리는 방법이 있습니까?myVariable?
별도의 함수를 만들고 구독 내에서 호출하는 것이 어떻습니까?
export class myClass {
myVariable: any;
myFunction() {
this.myService.getApi().subscribe(data => {
this.myVariable = data;
this.update()
});
this.update()
}
update(){
console.log(this.myVariable);
}
}
서버가 데이터를 반환할 때 헤드라인 등록이 실행되지만 헤드라인 등록 외부 코드는 동기적으로 실행됩니다.그게 이유다console.log실행되지 않은 상태에서.위의 대답은 당신의 일을 할 수 있지만 당신은 또한 사용할 수 있습니다..map그리고.return observable아래와 같이
서비스에서 호출한다고 가정합니다.
export class myClass {
myVariable: any;
// calling and subscribing the method.
callingFunction() {
// the console log will be executed when there are data back from server
this.myClass.MyFunction().subscribe(data => {
console.log(data);
});
}
}
export class myClass {
myVariable: any;
// this will return an observable as we did not subscribe rather used .map method
myFunction() {
// use .pipe in case of rxjs 6
return this.myService.getApi().map(data => {
this.myVariable = data;
this.update()
});
}
}
언급URL : https://stackoverflow.com/questions/50951779/angular-2-wait-for-subscribe-to-finish-to-update-access-variable
반응형
'IT' 카테고리의 다른 글
| Oracle에서 개체의 소유자를 어떻게 찾을 수 있습니까? (0) | 2023.06.17 |
|---|---|
| bash 스크립트에서 테이블 mariadb 업데이트 (0) | 2023.06.17 |
| 서비스 파일의 디스패치 돌연변이 (0) | 2023.06.17 |
| 파이썬에서 파일을 목록으로 읽는 방법은 무엇입니까? (0) | 2023.06.17 |
| PHPExcel 라이브러리를 대형으로 설치하려면 어떻게 해야 합니까? (0) | 2023.06.17 |