在此之后,我实现了角度可观测数据服务
tutorial
Theme
对象在
Theme component
topbar component
与我相反
Category
Category component
topbar组件
topbar组件
以下是我的模型实现:
export class Theme {
_id: string;
name: string;
description: string;
iconCode: string;
categories: Category[];
createdAt: Date;
updatedAt: Date;
export class Category {
_id: string;
name: string;
description: string;
createdAt: Date;
updatedAt: Date;
我的
CategoryStoreService
export class CategoryStoreService {
private _categories: BehaviorSubject<Category[]> = new BehaviorSubject<Category[]>([]);
private dataStore: {
categories: Category[]
};
constructor(private categoryBackendService: CategoryBackendService) {
this.dataStore = { categories: [] };
this._categories = new BehaviorSubject<Category[]>([]);
}
get categories() {
return this._categories.asObservable();
}
addThemeCategory(themeId: string, category: Category) {
this.categoryBackendService.addThemeCategory(themeId, category).subscribe(
res => {
this.dataStore.categories.push(res);
this._categories.next(Object.assign({}, this.dataStore).categories);
},
err => console.log('Error creating the category')
);
}
我的
ThemeStoreService
export class ThemeStoreService {
private _themes: BehaviorSubject<Theme[]> = new BehaviorSubject<Theme[]>([]);
private dataStore: {
themes: Theme[]
};
constructor(private themeBackendService: ThemeBackendService) {
this.dataStore = { themes: [] };
this._themes = new BehaviorSubject<Theme[]>([]);
}
get themes() {
return this._themes.asObservable();
}
/**
* Get the themes and their categories from the server and load it to the
* data store
*/
getThemes() {
this.themeBackendService.getThemes().subscribe(
res => {
this.dataStore.themes = res;
this._themes.next(Object.assign({}, this.dataStore).themes);
},
err => console.log("Error retrieving the themes")
);
}
我订阅了我的
储备
在
app.component.ts
代码如下:
export class AppComponent implements OnInit {
themes$: Observable<Theme[]>;
constructor(private themeStoreService: ThemeStoreService) { }
ngOnInit() {
// Subscribe to the themes
this.themes$ = this.themeStoreService.themes;
// Load all the themes
this.themeStoreService.getThemes();
}
及其模板:
<app-topbar [themes]="themes$ | async"></app-topbar>
<router-outlet></router-outlet>
主题
与我的
在野外
categories
topbar是一个接收
themes
通过@Input()属性,并使用以下代码显示主题和类别:
<li class="nav-item dropdown" *ngFor="let theme of themes">
<a class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span [innerHTML]="theme.iconCode"></span>
{{theme.name}}
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li *ngFor="let category of theme.categories">
<a class="dropdown-item" [routerLink]="['/threads']" [queryParams]="{ category: category._id }">
{{category.name}}
</a>
</li>
</ul>
</li>
和.ts文件
export class TopbarComponent {
@Input() themes: Theme[];
}
提前谢谢你的帮助。