2017-05-16 3 views
1

난 각도에서 시작하고 비동기 작업에 몇 가지 문제가 있습니다. 클래스 개인 값을 http 요청에 사용될 localstorage 키 값으로 설정하려고 시도하지만 http reuqest가 키가 저장소에서 검색되기 전에 실행됩니다. 나는 이온 성 네이티브 스토리지를 사용하고 있습니다. 이 작업을 구현하는 적절한 방법은 무엇입니까? 어떤 도움이라도 대단히 감사 할 것입니다. 당신은 저장 콜백이 호출 된 후 HTTP 요청 을 보낼 수 있습니다로컬 저장소의 각도 비동기 문제

export class EventService { 
constructor(private _http: Http, private _storage: Storage) { 
} 

private url = 'http://website.com'; 
private token : string; 

getEventsAction() { 
    this._storage.ready().then(() => { 
    this._storage.get('auth_token').then((val) => { 
     this.token = val; 
    }); 
}); 

let params = { 
    "query": { 
    "search_term": "", "page": 1 
    } 
}; 
let headers = new Headers(); 
headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
headers.append('Access-Control-Allow-Origin', '*'); 
headers.append('Auth-Token', this.token); 

let options = new RequestOptions({headers: headers}); 

return this._http.post(this.url + '/api/events/list', params, options) 
    .map((response: Response) => { 
    let events = response.json(); 
    if (events) { 
     return events; 
    } 
    }); 
} 
+0

코드에서 저장소의 키를 어디에서 검색하며 http 요청은 어디에서 수행합니까? – echonax

답변

0

: 다음은 내 코드입니다.

export class EventService { 
    constructor(private _http: Http, private _storage: Storage) { } 

    private url = 'http://website.com'; 
    private token : string; 

    getEventsAction() { 
     this.retrieveToken().catch(() => { 
      // You can log something here, the 'then' callback will be always executed anyway 
     }).then(() => { 
      this.sendHttpRequest(); 
     }); 
    } 

    private retrieveToken(): Promise<any> { 
     return this._storage.ready().then(() => { 
      return this._storage.get('auth_token').then((val) => { 
       this.token = val; 
      }).catch(() => { 
       // Set default token if storage.get() raised an exception 
       this.token = 'defaultToken'; 
      }); 
     }); 
    } 

    private sendHttpRequest() { 
     let params = { 
      "query": { 
       "search_term": "", "page": 1 
      } 
     }; 
     let headers = new Headers(); 
     headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
     headers.append('Access-Control-Allow-Origin', '*'); 
     headers.append('Auth-Token', this.token); 

     let options = new RequestOptions({headers: headers}); 

     return this._http.post(this.url + '/api/events/list', params, options) 
     .map((response: Response) => { 
      let events = response.json(); 
      if (events) { 
       return events; 
      } 
     }); 
    } 
} 
+0

감사합니다. 집에 돌아가서 피드백을 주 자마자 시험해 볼 것입니다! 건배 :) – trix87

+0

매력처럼 작동합니다! :) thanks :) – trix87

+0

이 코드와 관련하여 도움이 될만한 질문이 하나 더 있습니다. 이 경우 인증 키가 발견되지 않으면 set() 부분이 여전히 getEventsAction에서 실행되어야합니까? 토큰이 설정되지 않은 경우 this.sendHttpRequest가 .then() 부분 이후에 실행되지 않기 때문에이 질문을합니다. 토큰에 대한 기본 개인 값이없는 경우 (빈 문자열). 이것이 작동하는 방식이라면 이것이 실행될 수있는 해결책이 있습니까? 감사 ! – trix87

관련 문제