2017-11-11 1 views
0

패치를 가져 와서 JWT 토큰을 가져 와서 로컬 저장소에 저장합니다. 이 작동합니다.Aurelia - 두 번째 페이지가 완료되고 새 페이지가 렌더링 된 후 localStorage가 완료되는 두 개의 "가져 오기"관련 문제

그런 다음 초기 페치에 ".then"을 연결하고 다른 페치라는 함수를 통해 API에서 사용자 이름과 암호를 가져 와서 로컬 저장소에 저장했습니다.

마지막 ".then"는 루트를 새 루트로 재설정합니다. (작동) ... 그리고 JWT와 loggedIn의 첫 번째 localStorage 저장은 setRoot 호출이 시작되기 전에 완료됩니다. ...

내 문제는 localStorage에 사용자 이름을 저장하는 중입니다. 두 번째 가져 오기는 새로운 루트 페이지가 localStorage에서 사용자 이름을 얻으려고하는 생성자를 실행 한 후에 발생합니다. 두 번째 가져 오기가 아직 완료되지 않았으므로 localStorage의 'username'이 아직 설정되지 않았습니다 ...

루트를 재설정하기 전에 내 페치와 localStorage에 대한 모든 저장이 성공적으로 저장되었는지 어떻게 확인합니까?

여기에 내 초기 가져 오기를 수행하는 login.ts 파일이 있습니다.

login(username: string, password: string) { 
    this.userLogin.Username = username; 
    this.userLogin.Password = password; 

    // Lets do a fetch! 
    const task = fetch("/api/jwt", { 
     method: "POST", 
     body: JSON.stringify(this.userLogin), 
     headers: new Headers({ 'content-type': 'application/json' }) 
    }) 
     .then(response => response.json()) 
     .then(data => { 
      console.log("data - in FETCH: ", data); 
      localStorage.setItem(this.TOKEN_KEY, JSON.stringify(data)); 
      localStorage.setItem(this.LOGGED_IN, JSON.stringify("authenticated")); 

     }) 
     .then(() => { 
      this.saveUserDetail(); 
     }) 
     .then(() => { 
      console.log(" before redirect USERNAME_KEY): ", localStorage.getItem(this.USERNAME_KEY)); 
      this.router.navigate('/', { replace: true, trigger: false }); 
      this.router.reset(); 
      this.aurelia.setRoot('app/app/app'); 
     }) 
     .catch(error => { 
      this.clearIdentity(); 
     }); 

당신은 내가 세 번째 "그 때는"에서와 사등은 "그 때는"에 this.saveUserDetail()를 호출 것을 알 수가 나는 aurelia.setRoot을 ('...').

두 번째 가져 오기가있는 this.saveUserDetail() 함수가 여기에 있습니다.

saveUserDetail() { 
    const session = this.getIdentity(); 
    if (!session) { 
     throw new Error("No JWT present"); 
    } 
    const token = session.access_token; 

    const headers = new Headers({ 
     Authorization: `bearer ${token}`, 
     "Content-Type": "application/json; charset=utf-8" 
    }); 

    const task = fetch("/api/jwt/userDetail", { 
     method: "GET", 
     headers 
    }) 
     .then(response => response.json()) 
     .then(data => { 
      try { 
       console.log("data.stringify: ", JSON.stringify(data)); 
       localStorage.setItem(this.USERNAME_KEY, data.username); 
       localStorage.setItem(this.USERROLES_KEY, data.role); 
      } catch (Error) { } 

      console.log("localStorage.getItem(this.USERNAME_KEY): ", localStorage.getItem(this.USERNAME_KEY)); 
     }); 
} 

나는 사용자 이름에 대한 API로 돌아가야한다는 인상을 받고있었습니다. 어쩌면 내가 한 가져 오기 등 그것을 할 수있는 내가 거기에 "aurelia.setroot()를 수행하기 전에 모든로드 된 localStorage 가질 수있는 방법이 있습니까?

답변

1

return 추가 시도 그래서 this.saveUserDetail()에 의해 반환 된 - 오, , 당신은 너무 saveUserDetail

그래서

.then(() => { 
    return this.saveUserDetail(); 
}) 

또는

.then(this.saveUserDetail) // note, pass the function, don't call it 

과 변화를 약속을 반환해야 기다려 saveUserDetail

saveUserDetail() { 
    // all your code, then at the bottom of the function add: 
    return task; 
} 
+0

작동합니다. 같은 방법으로 가야했지만 가져 오기가 끝난 후 "반환 작업"을 알지 못했습니다. 마지막으로 새 루트에 사용자 이름이 표시됩니다. 고맙습니다. – si2030

관련 문제