持久类属性 Angular 5 [英] Persist class property Angular 5
问题描述
我有一个 SearchComponent (route:/search) 和 SearchDetailComponent (route:/search-detail:id).
I have an SearchComponent (route: /search) and SearchDetailComponent (route: /search-detail:id).
SearchComponent 包含一个搜索框(输入字段),我可以在其中键入任何文本以开始搜索.
The SearchComponent contains an searchbox (input field) where I can type any text to start a search.
现在在加载搜索结果并导航到 SearchDetail 页面后,我想保存我在搜索框中键入的搜索词.但仅在从详细信息页面路由回来之后.所以如果我从详细页面导航回来,我搜索的相同文本应该在搜索框中.
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?
推荐答案
您可以使用 Service
或 localStorage/Session Storage
来持久化数据.
You could either use a Service
or localStorage/Session Storage
for Persisting Data.
localStorage
和 sessionStorage
完成完全相同的事情并具有相同的 API,但是使用 sessionStorage
数据仅保留到窗口或选项卡已关闭,而使用 localStorage
时,数据会一直保留,直到用户手动清除浏览器缓存或您的网络应用程序清除数据为止.
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.
我建议你去@ngx-pwa/local-storage Angular 的异步本地存储
I would suggest you to go for @ngx-pwa/local-storage Async local storage for Angular
npm install @ngx-pwa/local-storage@5
在您的 RootModule 中注册
import { LocalStorageModule } from '@ngx-pwa/local-storage';
@NgModule({
imports: [
BrowserModule,
LocalStorageModule,
...
]
注入并使用
import { LocalStorage } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(protected localStorage: LocalStorage) {}
}
使用
let user: User = { firstName: 'Henri', lastName: 'Bergson' };
this.localStorage.setItem('user', user).subscribe(() => {});
在您来回导航后,只需使用这些方法之一设置/修补值 setValue()
和 patchValue()
都以 形式设置值
.FormGroup
的控制
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
.
服务
创建服务并将其注册到 Angular 模块而不是组件中.
Service
Create a Service and Register the it in an Angular module rather than a component.
如果您希望全局共享依赖项的实例并在应用程序中共享 state
,请在 NgModule 上配置它.
If you want an instance of a dependency to be shared globally and share state
across the application configure it on the NgModule.
您可以使用 Subject
或 BehaviorSubject
来完成它.
You could either use Subject
or BehaviorSubject
to accomplish it.
这篇关于持久类属性 Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!