12664

Angular2 carry over value of variable when changing pages

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(); }

Recommend

  • Get-AdComputer -filter parameter not accepting Get-Date output
  • QML cannot assign assign shared_ptr to [unknown property type]
  • Sending email through PHP mail function not working for long emails
  • How to use CKFetchNotificationChangesOperation?
  • Java array: Attribute size?
  • C++ usrsctp callback parameters null
  • Matrix problem Python
  • Upgrade to g++ 4.7 (with c++11 support): any ABI incompatibility?
  • Dynamically create AWS IoT topic
  • Using Delphi + Jedi, losing USB data when device sends it “too fast”
  • how to post with curl to REST/JSON service?
  • Paramiko SSHException Channel Closed
  • triggering user space with kernel
  • Replace last two characters in column
  • PushKit for VOIP iOS apps
  • Passing “get” parameters doesn't work, parameter not visible in the link
  • Pass Dictionary to Javascript array
  • ASP.NET MVC Application won't update some controllers
  • Multicolored edittext hint
  • How to assign byte[] as a pointer in C#
  • Redux Form - Not able to type anything in input
  • Button text different than value submitted in query string
  • Odoo 10 - Overriding unlink method
  • Calling Worksheet functions from vba in foreign language versions of Excel
  • Do I need to reset a Perl hash index?
  • How can I sort a a table with VBA with given text condition?
  • All Classes Conforming to Protocol Inherit Default Implementation
  • How would I use PHP exceptions to define a redirect?
  • Updating server-side rendering client-side
  • DirectX11 ClearRenderTargetViewback with transparent buffer?
  • Modifying destination and filename of gulp-svg-sprite
  • javascript inside java/jsp code
  • Deserializing XML into class C#
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Web-crawler for facebook in python
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Proper way to use connect-multiparty with express.js?
  • python draw pie shapes with colour filled
  • How to Embed XSL into XML