jeudi 1 juin 2017

should my angular2+ component data be an object or an observable?

Let's say I want to build an angular2+ component that fetches some thing form the api, and display its name. Thanks to some websocket connection, the thing can be updated anytime.

Which one of these two approaches is more idiomatic ?

First attempt: thing as an object:

Basically, the component subscribes to a websocket observable, and updates its own thing object when necessary. If child-components are used, then we will pass a Thing as an input.

interface Thing { name: string }

@Component({
  selector: 'app-thing',
  template: '<h1>  </h1>',
})
export class ThingComponent implements OnInit {
  public thing: Thing

  constructor(
    private route: ActivatedRoute,
    private thingService: ThingService,
  ) {}

  public ngOnInit() {
    this.route.params.subscribe(params => {
      this.thingService.get(params.id).subscribe(({thing}) => {
        this.thing = thing
      })
    })

    this.thingService.socketObservable().subscribe(newThing => {
      console.log('Thing has been updated !')
      this.thing = newThing
    })
  }
}

Second attempt: thing as a Subject:

Instead of having an objectthing: Thing, we now have thing: Subject<Thing> (Not shown here, but I'm using Subject instead of Observable so I can complete it in the ngOnDestroy method)

In this version, the template uses the async pipe, and child-components will receive an observable instead of an Thing object.

interface Thing { name: string }

@Component({
  selector: 'app-thing',
  template: '<h1>  </h1>',
})
export class ThingComponent implements OnInit {
  public thing: Subject<Thing>

  constructor(
    private route: ActivatedRoute,
    private thingService: ThingService,
  ) {}

  public ngOnInit() {
    this.thing = new Subject<Thing>()

    this.route.params.subscribe(params => {
      this.thingService.get(params.id).subscribe(({thing}) => {
        this.thing.next(thing)
      })
    })

    this.thingService.socketObservable().subscribe(newThing => {
      console.log('Thing has been updated !')
      this.thing.next(newThing)
    })
  }
}

From what I can say, both versions seem to work. I suspect thtey are not quite equivalent under the hook, but I lack knowledge to decide wether I should prefer the first one or the second one.

Any ideas ?

Aucun commentaire:

Enregistrer un commentaire