1

我正在观看@john_lindquist 的关于 RxJS 的蛋头教程,他强调了不包括业务逻辑而不是.subscribe()方法的观点。

因此,我正在创建一个 canActivate 防护来防止用户进入无效路由,并且我不禁将逻辑构建到 subscribe 方法中。有一个更好的方法吗?

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();
  }

}
4

1 回答 1

6

为了回答你的问题,有一种更“RxJS 友好”的方式来做你想做的事。(“更好”是一个见仁见智的问题)。所以,例如,如果我正在实现这个,我会这样做:

canActivate(route: ActivatedRouteSnapshot) {

  // canActivate can return an Observable - 
  // the Observable emitting a true or false value
  // is similar to returning an explicit true or false
  // but by returning the observable, you let the router
  // manage the subscription (and unsubscription) instead of doing it yourself
  // doing this removes the need for the `unsubscribe` in your code
  return this.apollo.watchQuery({
    query: GQTicketId,
    variables: {
      _id: +route.params['id']
    }
  })
  // there should be no arguing about this point -
  // you only care about the data['ticket'] property,
  // not the entire data object, so let's map our observable
  // to only deal with ticket
  .map(response => response.data.ticket)
  // you want to do a side effect if ticket is falsy
  // so the do operator is your best friend for side effect code
  .do(ticket => {
    if(!ticket) {
      this.router.navigate(['provision/requests/error/404']);
    }
  })
}

没有评论:

canActivate(route: ActivatedRouteSnapshot) {

  return this.apollo.watchQuery({
    query: GQTicketId,
    variables: {
      _id: +route.params['id']
    }
  }).map(response => response.data.ticket)
    .do(ticket => {
        if(!ticket) {
          this.router.navigate(['provision/requests/error/404']);
        }
      })
    }

我看过约翰的视频,但现在不记得具体内容了。但是,RxJS 的关键之处在于,通过正确使用运算符,您通常可以删除大量原本会在您的subscribe方法中结束的命令式代码。这并不意味着使用subscribe本身就是不好的——只是有逻辑subscribe通常表明你没有充分利用 RxJS。

于 2017-04-12T01:41:38.040 回答