
Question:
I have a multi-page website (using the router) and would like to carry a variable value over from one page to the other.
On my contact form page, I have the following code:
testName:string = "hello";
ngOnInit()
{
this.dataService.Stream
.subscribe(
(city:City) => this.processData(city),
(err) => console.log('Error at processing data'),
() => console.log('Complete...')
)
}
processData(city:City)
{
console.log('the city name is: ', this.testName);
this.problematicCity = city;
this.testName = city.name;
console.log('received data for city: ', this.testName);
}
When I'm on the main page and send a city to the data service, I get the following output in the console:
the city name is: hello
received data for city: Luxemburg
I therefore know that information is passed on correctly.
However, when I then go to the contact page, testName
is changed back to 'hello'.
How do I prevent this from happening?
I have tried not initiating testName, but then I get the error: assignment to undeclared variable string
.
Moving testName:string = "hello";
to ngOnInit
also results in the same error.
<strong>Addition:</strong> This is my data service:
//data.service.ts
import {Subject} from 'rxjs/Subject';
import {Injectable} from 'angular2/core';
import {City} from '../model/city.model';
@Injectable()
export class DataService
{
Stream:Subject<City>;
constructor()
{
this.Stream = new Subject();
}
}
Answer1:You're creating a Subject
: this is a proxy that serves as an observable and an observer.
When you create a [Behavior|Replay]Subject
, you're creating a <strong>hot stream</strong> : any observer subscribing to it will receive the last value of it.
This is different from a <strong>cold stream</strong>, like HTTP calls, where the whole stream is transmitted : once you have subscribed to it and the observable is finalized, you're not subscribed to it anymore.
In code words, it means everytime you create an instance of your contact component, you create a new subscription, and the subscription code is ran everytime you call next
on your subject <strong>OR</strong> when you create a new subscription (hot streams get the latest value of the stream at their first subscription).
To avoid that, you can either limit your subscription to a single call, or delete your subscrpition at component destruction. I recommend the latter :
ngOnInit() {
this.streamSubscription = this.dataService.Stream.subscribe(...);
}
ngOnDestroy() {
this.streamSubscription.unsubscribe();
}