问题描述
我有一个SearchComponent(路线:/search)和SearchDetailComponent(路线:/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页面之后,我想保存我在搜索框中键入的搜索词.但是从详细信息页面路由回去后,仅.因此,如果我从detai页面导航回去,则我搜索的相同文本应该在搜索框中.
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
时,数据一直保留到直到用户手动清除浏览器缓存,或者直到您的Web应用清除数据为止.
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
的form control
中设置值.
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.
Using Subject
Using BehaviorSubject
这篇关于持久类属性Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!