Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - turn 'activatedRoute.params' into promise

I am trying to turn the observable for params that I get off of the ActivatedRoute into a promise but haven't had any luck. I have been able to turn http requests into promises successfully:

this.riaService.getAdvisorsForState(this.activeState)
    .then(rias => {
        this.riasForState = rias.json();
        console.log(this.riasForState);
    });
// this all works ^

But I have not been able to turn the 'activatedRoute.params' into a promise:

export class InvestmentAdvisorStateComponent implements OnInit {

    constructor(private activatedRoute: ActivatedRoute, private riaService: InvestmentAdvisorService) { }

    getStateFromUrl() {
        this.activatedRoute.params
            .toPromise()
            .then(params => {
                console.log('HERE',params)
            });
    }
// this does not work for me ^

This is what I have right now:

getStateFromUrl() {
    this.activatedRoute.params
        .subscribe((param: any) => {
            this.activeState = param['state'];
        });
}
// works ^

I am hoping to implement this as a promise thought so I can .then off of it. Any help on how to do this is greatly appreciated.

like image 509
georgej Avatar asked Jan 05 '23 06:01

georgej


1 Answers

The main difference between observable and promise is, that observable can emit multiple events while a promise only emits a single event.

To make your example work, I assume you are only interested in the first event.

getStateFromUrl() {
    this.activatedRoute.params
        .first()
        .toPromise()
        .then(params => {
            console.log('HERE',params)
        });
}

This way the promise created with toPromise() is completed with the first params event.

like image 136
Günter Zöchbauer Avatar answered Jan 13 '23 10:01

Günter Zöchbauer