是否可以在Observable订阅方法中包含逻辑?

tec*_*rek 1 observable rxjs apollo-client angular

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

因此,我正在创建一个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();
  }

}
Run Code Online (Sandbox Code Playgroud)

sno*_*ete 5

要回答你的问题,有一种更"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']);
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

没有评论:

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']);
        }
      })
    }
Run Code Online (Sandbox Code Playgroud)

我观看了约翰的视频,但此时记不起具体细节.但是,RxJS的关键点在于,通过正确使用运算符,您通常可以删除大量的命令式代码,否则这些代码最终会出现在您的subscribe方法中.这并不意味着使用subscribe本身就是坏事 - 只是逻辑输入subscribe通常表明你没有将RxJS用于最佳潜力.