2017-05-18 3 views
0

C# 및 Angular1 코드 작성 경험이 있지만 Angular2 + 및 RxJs는 새로운 것입니다.Angular4 Http 처리에 대한 모범 사례 Obserable

저는 Angular4 로그인 구성 요소를 작성 했으므로 login 메소드의 결과를 observable의 map 함수에 캐싱하여 코드 냄새를 맡은 것처럼 보입니다.

은 내가 LoginComponent가에 로그인을 호출하는 AuthenticationService 있습니다

login(username: string, password: string): Observable<User> { 
return this.http 
    .post('/api/users/login', { username: username, password: password }) 
    .map((response: Response) => { 

    let loginResult = response.json(); 
    this.user = loginResult.user as User 

    localStorage.setItem(tokenStorageName, loginResult.token); 

    return this.user; 
    }) 
    .catch(this.handleError); 

}

이 때문에 지금까지 그 단지를해야 내가 아는지도 기능의 상태를 저장하는 이상한 느낌

번역 기능. 나는 사용자 데이터를 원한다면 다른 서비스 호출을 할 필요가 없도록 로그인 결과에서 돌아온 사용자와 토큰을 캐싱하려고합니다. LoginComponent이 AuthenticationService 또는 UserCache에 SETUSER를 호출하는

login() { 
this.isLoading = true; 
this.authenticationService.login(this.model.username, this.model.password) 
    .subscribe(
    result => { 
    let returnUrl = this.activatedRoute.snapshot.queryParams['returnUrl'] || '/' 
    this.router.navigate([returnUrl]); 
    }, error => { 
    if (error != null && error.code == unauthorizedCode) { 
     this.error = 'Username or password incorrect'; 
    } 
    else { 
     this.error = 'Error logging in'; 
    } 
    this.isLoading = false; 
    }); 

그것은 또한 느낌이 좋지 않습니다 여기

은 로그인 구성 요소의 논리이다.

모범 사례에 대한 조언을주세요. 뭔가를 시도

답변

0

는 :

login(username: string, password: string): Observable<User> { 
    let o = this.http 
     .post('/api/users/login', { username: username, password: password}) 
    //uncomment if you have multiple subscribers, otherwise http request is executed multiple times 
     //.share() 
    ; 

    o.subscribe(
     (response: Response) => { 
      this.user = loginResult.user as User; 
      localStorage.setItem(tokenStorageName, loginResult.token); 
     }, 
     (response: Response) => this.handleError(response) 
    ); 

    return o.map(response: Response => response.json()); 
} 
+0

share()가 일반적으로 생각하고있는 것인가, 아니면 약간의 실수를 저지르는 것인가? (예 : next =>/*이 값으로 무엇인가 할거 * /) : .do 관찰의 원칙? LoginSerponent와 AuthenticationService 사이에 UsersService를 두어 AuthenticationService의 observables를 확인하고 거기에 캐싱을 수행하는 대체 접근법이 있다고 가정합니다. 그러나 이것은 정상에 조금 보인다? –

+0

두 가지 해결책 ('do()'과'share()')에 대해서는 RxJs 문서를 참조하십시오 : https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/share. md –

+0

죄송합니다, 5 분만 의견을 편집 할 수 있습니다 ... 제 경우에는 각 요청에 대해'showLoader()'를 수행합니다. 모든 CRUD 자원은 성공 및 오류 처리기를 공유합니다. 그러나 각 CRUD 구성 요소에는 자체 성공 및 오류 처리기가있을 수 있습니다. 만약 내가'subscribe()'를 두 번 ('shared'와'specific' 논리에 대해) 사용한다면, 적어도'showLoader()'가 두 번 실행됩니다. 여러 개의'do()'를 사용하여 코드를 작성할 수 있지만 반드시 제한해야하는 이유는 무엇입니까? –