Event doesnt trigger on RxJs subscribe

I’m following this guide - https://angular.io/docs/ts/latest/guide/server-communication.html - in building an Observable http request to get some data from an [aws public api gateway] url. I can correctly load the options, but there are 2 problems. 1) I can’t get my onChange event to trigger (ui just flickers, never selects the item), and 2) I dont know which life cycle hook should initialize someItem as a default property (in constructor?) after the options are loaded.

private errorMessage: string;

**public someItem: any;**
public options: any = [];

constructor(private myService: ServiceProvider) { }

ngOnInit() {
  this.getSomeOptions();
}

getSomeOptions() {
   var self = this;
   this.myService.serviceHandler('myKey')
       .subscribe(data => { 
           self.options = data;
           self.someItem = data[0];
   }, error => this.errorMessage = <any>error);
}

onChange(e) {
    this.someRequest.emit(e && e.value);
}

Here’s my DOM -

 <ion-segment [(ngModel)]="someItem" (ionChange)="onChange($event)">
    <ion-segment-button *ngFor="let item of options" [value]="item">
       {{item.label}}
    </ion-segment-button>
 </ion-segment>

If I set someItem inside the subscribe, the ion-segment defaults to only one option, and I still can’t get into my onChange event.

Read this thread. Incidentally, you don’t need to bother with all that “self” stuff in getSomeOptions(), and please stop abusing any.

Thanks again! On a side note - instead of abusing any while learning - is it better to just leave it out completely, or really dig in and make the effort to create a type if there’s one. In my case, the options are an array of objects, so

type MyType = {
   name: string;
   label: string;
   slug: string;
}

public options: MyType[]; ?

I thought any/types in typescript weren’t enforced in javascript, its just a novelty/best practice for future proofing? (Which begs the question, when will that be)? You don;t have to answer, you’re a star, thanks again!

It’s much better to make a type, although I use interface instead of type because interfaces are more flexible. I highly recommend also enabling noImplicitAny in your tsconfig.json’s compilerOptions, which will yell at you if you “just leave it out completely” or forget to declare function return types.

Enforced at runtime, no, but if you get in the habit of typing everything, two really great things happen:

  • Many stupid mistakes that would have required laborious runtime debugging become compile-time build failures (or even type-time complaints from your IDE, if it’s smart enough). This will save you tons of time and frustration in the long run.

  • Your code becomes much more readable and self-documenting. You can instantly look at a function and see how it is supposed to be used and what you can expect it to give you back.

1 Like