Search code examples
aurelia

pass data to another route without messing with url


DISCLAIMER: I'm a noob.. sorry

Say I have 2 different components that are siblings:

comp1 and comp2

I wish to route from comp1 to comp2 with a bunch of data. How can I achieve this without getting a fugly url-bar containing everything?

I've tried using a separate class, lets call it DataTransmitter:

data-transmitter.js:
export class DataTransmitter {
    constructor() {
    this.val= "a";
    }
}

comp1.js:
import { DataTransmitter } from './data-transmitter';

@inject(DataTransmitter)
export class comp1{
    constructor(DataTransmitter){
        this.DataTransmitter = DataTransmitter;
    }

    someMethod(){
        this.DataTransmitter.val = "b";
        console.log('comp1: ' + this.DataTransmitter.val);
    }
}


comp2.js:
import { DataTransmitter } from './data-transmitter';

@inject(DataTransmitter)
export class comp2{
    constructor(DataTransmitter){
        this.DataTransmitter = DataTransmitter;
    }

    someMethod(){
        console.log('comp2: ' + this.DataTransmitter.val);
    }
}

This gives me the output:

comp1: b
comp2: a

I've also tried messing around with EventAggregator, but no success.

Is there some way of routing with parameters WITHOUT having a url that looks like site/comp2?data=stuff&things=otherstuff&params=values&more=etc?


Solution

  • You absolutely want to use a singleton class and then inject it inside of whatever components you need your data. The link that Gaby posted is definitely what you want to do.

    The reason your posted code does not work is because you're attempting to use the inject decorator, but you're not importing it. Please see this working example of what you are trying to do on Gist.run here. I have two components, you can click to route between them and set the value. You'll notice the set value remains when you navigate back and forth.