Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

typescript - Persist class property Angular 5

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...