Persist class property Angular 5

2019-09-21 07:07发布

问题:

I have an SearchComponent (route: /search) and SearchDetailComponent (route: /search-detail:id).

The SearchComponent contains an searchbox (input field) where I can type any text to start a search.

Now after loading the search results an navigating to the SearchDetail page, I want to save the search term I typed into the searchbox. But only after routing back from the Detail page. So if I navigate back from detai page, the same text I searched for should be in the searchbox.

The searchbox should be empty while navigating to the search site by any other page.

Has anyone an example or suggestion how to implement that?

回答1:

You could either use a Service or localStorage/Session Storage for Persisting Data.

localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data.

I would suggest you to go for @ngx-pwa/local-storage Async local storage for Angular

For Angular 5:

npm install @ngx-pwa/local-storage@5

Register it in your RootModule

import { LocalStorageModule } from '@ngx-pwa/local-storage';

@NgModule({
  imports: [
    BrowserModule,
    LocalStorageModule,
    ...
  ]

Inject and use it

import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable()
export class YourService {

  constructor(protected localStorage: LocalStorage) {}

}

Usage

let user: User = { firstName: 'Henri', lastName: 'Bergson' };

this.localStorage.setItem('user', user).subscribe(() => {});

After you navigate back and forth just set/patch the values using one of these methods setValue() and patchValue() both sets the value in form control of FormGroup.

Service
Create a Service and Register the it in an Angular module rather than a component.

If you want an instance of a dependency to be shared globally and share state across the application configure it on the NgModule.

You could either use Subject or BehaviorSubject to accomplish it.

  1. Using Subject

  2. Using BehaviorSubject