Observable/http/async 콜로부터의 응답을 angular로 반환하려면 어떻게 해야 합니까?
서버에 http 요청을 하고 데이터를 가져오는 관찰 가능 데이터를 반환하는 서비스를 가지고 있습니다.이, 엔 항상 이 데이터를 받게 .undefined★★★★★★★★★★★★★★★★?
서비스:
@Injectable()
export class EventService {
constructor(private http: Http) { }
getEventList(): Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get("http://localhost:9999/events/get", options)
.map((res)=> res.json())
.catch((err)=> err)
}
}
컴포넌트:
@Component({...})
export class EventComponent {
myEvents: any;
constructor( private es: EventService ) { }
ngOnInit(){
this.es.getEventList()
.subscribe((response)=>{
this.myEvents = response;
});
console.log(this.myEvents); //This prints undefined!
}
}
비동기 호출에서 응답을 반환하려면 어떻게 해야 합니까?를 체크했습니다.게시했지만 해결 방법을 찾을 수 없음
이유:
undefined을 사용법,, the, 이, 이, 이, to, ,, ,, ,, ,, meaning, meaning, meaning, meaning, meaning, meaning, meaning, meaning, meaning, meaning, meaning, meaning, meaning, the, the, the, thegetEventList방법(주로 네트워크 속도에 따라 다름)을 지정합니다.
이제 http 콜을 보겠습니다.
this.es.getEventList()
"http"를 사용하여 한 후(""), "http" ("firesubscribe답변을 기다리고 있겠습니다.기다리는 동안 javascript는 이 코드 아래의 행을 실행하고 동기 할당/조작에 도달하면 즉시 실행합니다.
""에 "getEventList()
console.log(this.myEvents);
행이 즉시 실행됩니다. 그 는 리리 and and and and and and and and and and and and andundefined응답이 서버로부터 도착하기 전에(또는 처음에 초기화한 것에 대해서도).
이것은 다음과 같습니다.
ngOnInit(){
setTimeout(()=>{
this.myEvents = response;
}, 5000);
console.log(this.myEvents); //This prints undefined!
}
**Solution:** >So how do we overcome this problem? We will use the callback function which is the `subscribe` method. Because when the data arrives from the server it'll be inside the `subscribe` with the response.
따라서 코드를 다음과 같이 변경합니다.
this.es.getEventList()
.subscribe((response)=>{
this.myEvents = response;
console.log(this.myEvents); //<-- not undefined anymore
});
응답을 출력합니다.시간이 좀 지나서
**What you should do:**
뿐만 아니라 될 수 )에서 가 있습니다.이러한 조작은 모두 콜백(내부) 내에서 실행할 필요가 있습니다.subscribe기능)을 사용합니다.
또 하나 언급해야 할 것은, 만약 당신이 미국에서 왔다면Promise 'background', 'background'.then은 ''에 합니다.subscribe관측 가능.
**What you shouldn't do:**
비동기 조작을 동기 조작으로 변경하려고 하면 안 됩니다(할 수 없습니다).비동기 조작이 있는 이유 중 하나는 사용자가 그 기간에 다른 작업을 수행할 수 있을 때 조작이 완료될 때까지 기다리지 않기 위해서입니다.비동기 조작 중 하나를 완료하는데 3분이 걸린다고 가정합니다.비동기 조작이 없으면 인터페이스는 3분간 정지됩니다.
권장 자료:
이 답변의 최초 장점은 다음과 같습니다.비동기 콜에서 응답을 반환하려면 어떻게 해야 하나요?
그러나 angular2 릴리즈에서는 typescript와 observatible을 도입했기 때문에 이 답변에서는 observatible을 사용하여 비동기 요구를 처리하는 기본을 다루고 있습니다.
angular/javascript에서 http 호출은 비동기 작업입니다.따라서 http 콜을 발신하면 이 콜을 종료하고 다른 스레드로 다음 행 실행을 시작하기 위해 새로운 스레드가 할당됩니다.그렇기 때문에 정의되지 않은 값을 얻을 수 있습니다.이 문제를 해결하려면 아래 사항을 변경하십시오.
this.es.getEventList()
.subscribe((response)=>{
this.myEvents = response;
console.log(this.myEvents); //<-this become synchronous now
});
myEvents를 템플릿에서만 사용하는 경우 asyncPipe를 사용할 수 있습니다.
다음 예에서는 asyncPipe 및 Angular4 HttpClient의 예를 보여 줍니다.
관측치는 게을러서 값을 얻으려면 구독해야 합니다.코드에 올바르게 등록했지만 동시에 '등록' 블록 외부에 출력을 기록했습니다.그래서 '정의되지 않은' 것이다.
ngOnInit() {
this.es.getEventList()
.subscribe((response) => {
this.myEvents = response;
});
console.log(this.myEvents); //Outside the subscribe block 'Undefined'
}
따라서 서브스크라이브블록 내에 로그를 작성하면 응답이 올바르게 기록됩니다.
ngOnInit(){
this.es.getEventList()
.subscribe((response)=>{
this.myEvents = response;
console.log(this.myEvents); //Inside the subscribe block 'http response'
});
}
여기서 문제는 당신이 초기화하고 있다는 것입니다.this.myEvents안으로subscribe()비동기 블록입니다.console.log()막 나온subscribe()블록. 그래서console.log()전에 불려가는 것this.myEvents초기화됩니다.
console.log() 코드와 subscribe() 내부로 이동해 주세요.이것으로 종료됩니다.
ngOnInit(){
this.es.getEventList()
.subscribe((response)=>{
this.myEvents = response;
console.log(this.myEvents);
});
}
angular process async로 인해 결과가 정의되지 않았습니다. 다음과 같이 시도할 수 있습니다.
async ngOnInit(){
const res = await this.es.getEventList();
console.log(JSON.stringify(res));
}
또한 응답을 json 출력에 매핑해야 합니다.그렇지 않으면 일반 텍스트가 반환됩니다.이렇게 하면 됩니다.
getEventList(): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get("http://localhost:9999/events/get", options)
.map((res)=>{ return res.json();}) <!-- add call to json here
.catch((err)=>{return err;})
}
위의 서브스크라이브서비스 콜에서 서비스의 데이터를 설정하기 전에 이 값이 기록되기 때문에 정의되지 않았습니다.따라서 Ajax 콜이 종료될 때까지 기다렸다가 응답 데이터에서 데이터를 설정해야 합니다.
getEventList(): Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get("http://localhost:9999/events/get", options)
.map((res)=> res.json())
.catch((err)=> err)
}
여기서 myEvents 변수에 데이터가 설정되어 있을 때 로그를 만드는 서브스크라이브 메서드 내에 콘솔로그를 만듭니다.
ngOnInit(){
this.es.getEventList()
.subscribe((response)=>{
this.myEvents = response;
// This prints the value from the response
console.log(this.myEvents)
});
}
그러기 위해서는, 다음의 2개의 옵션이 있습니다.
배송 상세 어레이를 반환하는 서비스가 있다고 가정합니다.
getShippingPrices(): Observable<IShippingDetails[]> {
return this.http.get<IShippingDetails[]>('/assets/shipping.json');
}
1. 비동기 파이프 사용 : 결과를 템플릿에 표시하는 것만으로 간단한 방법
구성 요소 클래스에서 관측 가능한 변수를 직접 변수에 할당합니다.
export class ShippingComponent implements OnInit {
shipOptions1 = this.cartService.getShippingPrices();
constructor(private cartService: CartService) {}
ngOnInit() {}
}
다음으로 템플릿에서 비동기 파이프를 사용합니다.
<div *ngFor="let s of shipOptions1 |async">
<label>{{s.type}}</label>
</div>
참조: 이 URL의 네 번째 포인트를 확인합니다.https://angular.io/start/start-data#configuring-the-shippingcomponent-to-use-cartservice
2. Subscribe 사용 : 조작을 하거나 비즈니스 로직을 on/from 응답으로 하고 싶은 경우
export class ShippingComponent implements OnInit {
shipOptions2: IShippingDetails[] = [];
constructor(private cartService: CartService) {}
ngOnInit() {
this.cartService.getShippingPrices().subscribe(response => {
this.shipOptions2 = response;
//console.log(this.myEvents);
//All other code using shipOptions2
});
}
}
이 방법을 시도해 볼 수 있습니다.
let headers = new Headers({'Accept': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http
.get(this.yourSearchUrlHere, options) // the URL which you have defined
.map((res) => {
res.json(); // using return res.json() will throw error
}
.catch(err) => {
console.error('error');
}
언급URL : https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular
'programing' 카테고리의 다른 글
| 플러그인 가져오기를 로드하지 못했습니다. 'eslint-plugin-import' (0) | 2023.03.20 |
|---|---|
| WordPress에서 jQuery로 아코디언을 작성하려면 어떻게 해야 합니까? (0) | 2023.03.20 |
| joke.fn() 메서드와 joke.spyOn() 메서드의 차이점은 무엇입니까? (0) | 2023.03.20 |
| JSON 스키마: "all of"과 "additionalProperties" (0) | 2023.03.20 |
| 탭 대신 공간을 사용하도록 Eclipse를 변경하려면 어떻게 해야 합니까? (0) | 2023.03.20 |