2017-09-11 4 views
0

오늘 Angular에서 이상한 동작이 발생했습니다.angular2 구성 요소로드 문제

API를 사용하여 서버에서 데이터를 가져 오는 응용 프로그램이 있습니다. 다음은 내가 생각하는 내 문제에 대해 중요한 코드 파트입니다.

ID 중 하나를 사용하여 ID의 세부 정보 페이지로 이동 한 후 다른 ID를 사용하여 JSON을 가져옵니다. 이 페이지에서 나는 goback() 함수를 사용하여 목록에 다시 도달합니다.

첫 번째로드에서는 tempPromotion이 비어있는 상태로 돌아간 후에 API 데이터가 아무런 문제없이 저장됩니다. 콘솔 오류가 없습니다.

무엇이 문제 일 수 있습니까?

ngOnInit(): void { 
    // This is where i save the data from the API Call 
    this.promotionListService.getList().then((data) => { 
     this.tempPromotion = data; 
     this.tempPromotion = this.tempPromotion['response_payload']; 
     console.log(this.tempPromotion); 
    }); 
} 

    // This is the back Method which is called after a button click 
goback() { 
    this.location.back(); 
} 


    //Get List Method define the API call 
getList(): Promise<any> { 

    let Id = '1'; 
    let serviceDec = "PromotionList"; 

    return this.ApiClientService.getAPIObject(Id, serviceDec); 
} 


    // get APIObject makes the call 
getAPIObject(param: string, serviceDec: string) { 

    // Header mit Key aus LocalStorage 
    var header = new Headers(); 
    header.append('Content-Type', 'application/json'); // immer zu erst Content-Type 
    header.append('x-api-key', this.key); 

    let options = new RequestOptions({ headers: header }); 
    var urlTemp = this.url; 
    switch (serviceDec) { 

     case 'voucher': 
      urlTemp = urlTemp.concat('?promotionId='+param); 
      return this.http.get(urlTemp, options) 
       .toPromise() 
       .then((response: Response) => response.json()) 
       .catch(this.handleError); 

     case 'PromotionList': 
      urlTemp = API_CLIENT[2]; 
      return this.http.get(urlTemp, options) 
       .toPromise() 
       .then((response: Response) => response.json()) 
       .catch(this.handleError); 

     case 'salesChannelList': 
      urlTemp = API_CLIENT[3].concat('?mode='+param);; 
      return this.http.get(urlTemp, options) 
       .toPromise() 
       .then((response: Response) => response.json()) 
       .catch(this.handleError); 


     default: 
      console.error('An error occurred. Wrong service declaration.'); 

    } 
} 

답변

0

getList()는 관찰 할 수 있습니까? 그래서 당신은 이런 식으로 가입해야하는 경우 :

ngOnInit(): void { 
    // This is where i save the data from the API Call 
    this.promotionListService.getList().subscribe((data) => { 
     this.tempPromotion = data; 
     this.tempPromotion = this.tempPromotion['response_payload']; 
     console.log(this.tempPromotion); 
    }); 
} 

그들이 subscribe 에드을 때까지 Observables은 실제로 API에 떨어져 요청을 발생하지 않는 것을 기억하는 것이 중요하다. 따라서 구독을 설정하기 전까지는 관찰 대상에서 데이터를 수신하지 않습니다. 왜 어떤 오류가 발생하지 않았는지 설명 할 수 있습니다.

+0

'getList()'가 약속을 반환합니다. – sHamann

+0

내가 돌아 왔을 때 목록 구성 요소가 다시 작성된다는 것을 확인 했습니까? 어떤 이유로 인해 구성 요소가 경로간에 지속될 수 있습니다. 즉, ngOnInit은 페이지가 처음로드 될 때만 실행 중이며 정체 상태에있는 것을 의미합니다. 왜 tempPromotion 속성이 비어 있는지 모르겠다. – joshrathke

+0

'getList()'함수를 게시 할 수 있습니까? – joshrathke