我在RxJS上觀看了@ john_lindquist的egghead教程,他強調了不包括商業邏輯而不是.subscribe()
方法的觀點。可以在Observable訂閱方法中包含邏輯嗎?
因此,我創建了一個canActivate警衛以防止用戶進入無效路由,並且我忍不住建立了訂閱方法的邏輯。有一個更好的方法嗎?
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { Subject } from 'rxjs/Subject';
import { Apollo, ApolloQueryObservable } from 'apollo-angular';
import { GQTicketId } from './ticket.model';
@Injectable()
export class TicketRouteActivatorService implements CanActivate {
public ticket;
private returnTrue: Subject<Boolean> = new Subject<Boolean>();
private ticketSubscription: Subscription;
constructor(private apollo: Apollo,
private router: Router) { }
canActivate(route: ActivatedRouteSnapshot) {
this.ticketSubscription = this.apollo.watchQuery({
query: GQTicketId,
variables: {
_id: +route.params['id']
}
}).subscribe(({data})=>{
this.ticket = data['ticket'];
// this doesn't seem right, atleast based on the guidance from John Linquidst. Should this logic be "Rx'd" some how?
if(!this.ticket) {
this.router.navigate(['provision/requests/error/404']);
} else {
this.returnTrue.next(true);
}
}
);
if (this.returnTrue) return true;
}
// do we need to unsubscribe?
ngOnDestroy():void {
this.ticketSubscription.unsubscribe();
}
}
_「我在看RxJS上的@ john_lindquist的egghead教程,他強調了不包括busienss邏輯而不是.subscribe()方法的觀點。」_ - 他的推理是什麼? –
在代碼片段中實現的一個主要問題是它假定'subscribe'是同步的。您應該從'canActivate'返回observable並讓路由器實現訂閱它(如下面的答案)。 'canActivate'可以返回布爾值,承諾或可觀察值。 – cartant