思路:
建一个全局共享服务,在进入详情时将列表页的状态存到共享服务里,从详情返回列表页面在页面初始化时从公共服务中获取页面数据进行页面初始化。
1.共享服务创建;
- 创建服务命令ng g s 服务位置/名称 (缩写g:generate,s:service)
- 要想在其他组件中使用服务,需要在根模块中app.module.ts中引入并配置服务;
import { DataService } from './data.service';
@NgModule({
providers: [DataService],
})
export class AppModule {}
- 然后在服务service.ts中就可以写公共方法了;
- 然后在其他组件中使用的时候,首先在组件中引入然后在构造函数中注册;
import { Component } from '@angular/core';
// 1. 引入
import { DataService } from '../data.service';
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
})
export class AComponent {
// 2. 注册
constructor(public dataService: DataService) {}
}
2.保持状态逻辑实现
保存状态功能使用的时rxjs
中的BehaviorSubject,实现原理
存储最后一条数据或者初始默认值,并会在订阅时发送其当前值;
service.ts代码实现
import { Injectable } from '@angular/core';
// 1.引入
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class DataService {
// 2.创建subject
subject: BehaviorSubject<any> = new BehaviorSubject<any>({
page: 1,
list: [],
...
});
constructor() {}
}
页面组件代码逻辑;
import { Component } from '@angular/core';
// 1. 引入
import { DataService } from '../data.service';
@Component({
selector: 'app-a',
templateUrl: './a.component.html',
})
export class AComponent {
// 2. 注册
constructor(public dataService: DataService) {}
public data = null;
ngOnInit() {
// 3. 订阅
this.subscription = this.dataService.subject.subscribe((data) => {
this.data = data;
});
}
send(): void {
// 3. 保存数据
this.dataService.subject.next({
page: 4,
list: [{name: '123'}],
...
});
}
ngOndestry(): void {
// 4. 取消订阅
this.subscription.unsubscribe();
}
}
延伸:
共享服务还可以用于组件之间的通信,相较于普通的组件之间通过属性,和事件进行传值,在组件进行多层嵌套时,共享服务要方便很多。