当我需要在Angular项目中使用组件之间的一些数据时,我遇到了问题.我读到使用共享数据服务是一个很好的 Select ,所以我试图实现它,但我不能.
在项目开始时,我从http请求中获取了一些类别. 这些类别需要在项目的标题和正文中使用. 所以我在app.component.ts中获取分类
constructor(
public _categoryService: CategoryService,
private _dataService: DataService
){
this.getCategories();
}
getCategories(){
this._categoryService.getCategories().subscribe(
response => {
if(response.status == 'success'){
this.categories = response.categories;
this._dataService.setCategories(this.categories);
let categories = this._dataService.getCategories();
console.log(categories);
}
},
error => {
console.log(<any>error);
}
);
}
app.component.html
<app-header [categories]="categories"></app-header>
<!-- CONTENT -->
<router-outlet></router-outlet>
<app-footer></app-footer>
在标题中,我列出的类别没有问题.但我想在分类页面组件中列出它们. 我不能在中添加类别,这就是为什么我使用_dataService.
但当我点击类别路由链接
// ROUTES DEFINITIONS
const appRoutes: Routes = [
{ path: '', component: PageHomeComponent },
{ path: 'categories', component: PageCategoriesComponent },
];
我无法获取PageCategoriesComponent中的类别
constructor(
private _dataService: DataService
) { }
ngOnInit() {
let categories = this._dataService.getCategories();
console.log(categories);
}
在Chrome控制台中,我看到了第一个console.log是page—categories—component的值,第二个console.log是app.component的值,所有类别的值.
拜托,有人能解释一下发生了什么吗?
EDIT 我在page—categories.component.html中添加了一个按钮,以确保app.component中的请求已经完成,类别已经加载到dataService中,但它仍然返回一个空数组
<button (click)="clickButton()">get categories</button>
Page-categories.component.ts
clickButton(){
this._dataService.getCategories().subscribe((data) => {
this.categories = data;
console.log(this.categories);
});
}
SOLUTION 我在DataService中添加了这个:
@Injectable({
providedIn: 'root',
})
export class DataService {
private bSubject = new BehaviorSubject([]);
getCategories() {
return this.bSubject.asObservable();
}
setCategories(value: any) {
return this.bSubject.next(value);
}
}
我还从组件的提供程序中删除了DataService
@Component({
selector: 'app-page-categories',
templateUrl: './page-categories.component.html',
styleUrl: './page-categories.component.css',
providers: []
})