2017-12-04 9 views
-1

API 서비스에서 트랜잭션을받습니다. 트랜잭션 상태가 '보류 중'인 경우 조건은 트랜잭션 상태가 '완료'가 될 때까지 계속 다시로드하고 구독합니다. '거절 당했다'. 내 코드는 처음으로 작동하고 다음에 방문 할 때 페이지가 비어 있지만 데이터를 탈퇴하더라도 콘솔에서 데이터가 계속 실행됩니다.페이지를 새로 고치지 않고 조건부로 2 차원 상쾌한 실시간 데이터

여기 내 코드입니다 :

export class TransactionSummaryComponent implements OnInit, OnDestroy { 

    transaction: Models.Transaction = <Models.Transaction>{}; 

    cancelling: boolean = false; 
    goToPayment: boolean = false; 

    private dataRefreshSub: Subscription; 
    private subscribeToDataSub: Subscription; 
    private timer: Observable<any>; 

    constructor(
    private route: ActivatedRoute, 
    private router: Router, 
    private apiService: ApiService, 
    private zone: NgZone, 
    @Inject(PLATFORM_ID) private platformId: Object) { } 

    ngOnInit() { 
    if (isPlatformBrowser(this.platformId)) { 
     this.getTransaction(); 
    } 
    } 

    getTransaction() { 
    this.route.paramMap 
    .switchMap((params: ParamMap) => this.apiService.getTransaction(params.get('id'))) 
    .subscribe((transaction: Models.Transaction) => { 
     this.transaction = transaction; 

     if (this.transaction.status === 'Pending') { 
     this.refreshData(); 
     } 
    }); 
    } 

    refreshData() { 
    this.dataRefreshSub = this.route.paramMap 
     .switchMap((params: ParamMap) => this.apiService.getTransaction(params.get('id'))) 
     .subscribe((transaction: Models.Transaction) => { 
     this.transaction = transaction; 
     this.subscribeToData(); 
     }); 
    } 

    subscribeToData() { 
    this.zone.runOutsideAngular(() => { 
     NgZone.assertNotInAngularZone(); 
     this.timer = Observable.timer(1, 5000); 
     this.subscribeToDataSub = this.timer 
     .subscribe(() => { 
      this.refreshData(); 
     }); 
    }); 
    } 

    ngOnDestroy() { 
    if (this.dataRefreshSub !== undefined) { 
     this.dataRefreshSub.unsubscribe(); 
    } 
    if (this.subscribeToDataSub !== undefined) { 
     this.subscribeToDataSub.unsubscribe(); 
    } 
    } 
} 
+1

당신은 항상 안티 패턴이며, 가장 최근의 새로 고침 구독 만 구독을 거부하는 중첩 구독이 여러 개 있습니다. 다른 모든 구독에 대한 참조를 잃게됩니다. – bryan60

+0

그리고 무엇이 문제입니까? 너 뭐 해봤 니? 어떤 문제가 있습니까? 이것은 "내 코드 plz"웹 사이트를 수정하지 않습니다 .... – olivarra1

+0

@ bryan60 좋아, 당신이 의미하는 걸 가지고, 나는 모든 구독을 취소하는 시도를 줄 것입니다 –

답변

1

나는 부작용을 사용하지 않는 솔루션을 가지고 올 수없는,하지만 난 당신을 도울 수있다 생각합니다. Rxjs는 retry() 연산자를 가지고 있습니다.이 연산자는 던질 때 구독을 다시 실행합니다. 그래서 저는 다음과 같은 것을 할 것입니다 :

getTransaction() { 
    this.route.paramMap 
     .switchMap((params: ParamMap) => this.apiService 
      .getTransaction(params.get('id')) 
      .do(transaction => this.transaction = transaction) // Bad side effect here, I'm not sure how can this be cleaned out. 
      .map(transaction => { 
       if(transaction.status === 'Pending') { 
        throw 'Pending'; 
       } 
       return transaction; 
      }) 
      // use .retry(N) to retry at most N times. This will infinitely retry 
      .retryWhen(errors => errors) 
     ) 
     .subscribe((transaction: Models.Transaction) => { 
      // Here transaction will be 'Completed' or 'Rejected' 
     }); 
} 

이것으로 당신은 이론적으로 다른 모든 구독을 삭제할 수 있습니다.

+0

나는 당신의 해결책을 시도하지 않았지만 나는 그렇게 할 것입니다. 서비스에서 데이터를 새로 고치는 솔루션을 만들었지 만이 답변 (https://stackoverflow.com/questions/44947551/angular2-4-refresh-data-realtime/44947870#44947870)으로 구독하지 않았습니다. 브라이언이 내 탈퇴 문제에 관해 위에서 말했듯이, 나는 또한이 답변으로 탈퇴 방법을 업데이트했다 (https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription/41177163). # 41177163). 어쨌든 고맙습니다. –

+0

좋아, 솔루션도 잘 작동, 내가 말한대로 어떤 나쁜 부작용도 보지 않았다. –

+1

@ HoàngNguyễn 그 ".do (...)"는 "부작용"이라고 불린다. Rxjs 연산자는 순수한 의미이다. 따라서 스트림의 선언을보고 전체 그림을 알 수 있습니다. 그 사이에 "this"를 사용하는 것은 나쁜 습관으로 간주되며, 그것을 피하는 방법을 생각하는 것이 좋습니다. 다른 옵션이 없다면 괜찮습니다. 여러 번 그들은 완벽하게 받아 들여진다. (.switchMap (params => this.apiService.getTransaction (...))')처럼. 당신이 완벽한 깨끗한 코드가 아니라면 너무 많이 걱정하지 마십시오. – olivarra1