-->

angular 2 retain state from URL after redirect

2020-08-01 06:37发布

问题:

I start my angular app's index.html file at /app/123 and want to redirect to the controller handling /app with 123 to retain the information about what was queried initially.

How can this be accomplished?

回答1:

You have several choices:

1) You can retain information on a route using query parameters. That allows you to pass the same parameters back and forth between components.

2) Alternatively, you can build a service to hold onto your shared data. Services are a great way to hold onto data for your application. (But PLEASE don't use BehaviorSubject. It is completely unnecessary in most scenarios.)

I have an example service here:

https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

The basic service looks like this:

import { Injectable } from '@angular/core';

@Injectable() 
export class DataService {
  serviceData: string; 
}

And a plunker here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview