我在我的项目中有标签组件,并且我在其他组件中重用了该组件。在我的标签组件ngOnInit中,我调用了backend来获取所有现有的标签。我现在的问题是,调用应用于所有其他组件,即使除了编辑组件之外的其他组件不需要调用。因为我只需要后端调用来显示编辑组件的现有标记,所以我尝试将该调用移动到编辑组件ngOninit,但它不再显示现有的标记。如果我能得到任何关于如何解决这个问题的帮助或建议,我将不胜感激。
标记组件TS
ngOnInit(): void {
this.tagService.getAllTagsByType('user').subscribe((normalTags) => {
this.loading = true;
if (normalTags)
this.allnormalTags = normalTags;
this.allnormalTags.forEach(normalTags => {
this.allTagNames.push(normalTags.tag);
});
this.loading = false;
})
}如果我在标签组件中添加此调用,它会在下拉列表中显示所有现有标签。我试图将其移动到编辑组件ngOnIt,因为我只希望Eidt组件使用该调用,但它不再显示现有的标签。
Tags.Service.ts
getAllTagsByType(tagType: any){
return this.http.get<Tag[]>(`${environment.api.chart}/tags/all/${tagType}`).pipe(first());
}发布于 2020-06-24 04:13:42
您可以尝试设置一个标志来使用@Input触发后端调用。
tags.component.ts
import { Component, OnInit, Input } from '@angular/core';
export class TagsComponent implements OnInit {
@Input() getAllTags = false;
ngOnInit(): void {
if (this.getAllTags) { // <-- check here
this.tagService.getAllTagsByType('user').subscribe(
(normalTags) => {
this.loading = true;
if (normalTags)
this.allnormalTags = normalTags;
this.allnormalTags.forEach(normalTags => {
this.allTagNames.push(normalTags.tag);
});
this.loading = false;
},
error => {
// handle error
}
);
}
}
}现在,当您希望进行后端调用时,将值true传递给getAllTags。由于在ngOnInit之前触发了ngOnChanges钩子,因此如果没有在组件选择器中传递该属性,则不会进行调用。
<!-- edit component -->
<mc-tags
[getAllTags]="true"
[workspace]="workspace"
[removable]="true"
[selectable]="true"
[canAdd]="true" ]
[editMode]="true"
(added)="tagAdded($event)"
(removed)="tagRemoved($event)"
> </mc-tags>
<!-- other components -->
<mc-tags [workspace]="workspace"></mc-tags>发布于 2020-06-24 04:25:18
尝试使用RxJS。您应该将TagService中的标记数据作为主题(可观察)。顺便说一句,最好是将数据存储在服务层中。
TagService:
@Injectable({
providedIn: 'root'
})
export class TagService {
tagsSource = new BehaviorSubject<Tag[]>(null);
allnormalTags$ = this.tagsSource.asObservable();
getAllTagsByType(type: string){
http.request.subscribe(resultData => this.tagsSource.next(resultData))
}
}然后,在您的组件中,您可以检查数据是否已经加载,并且不会再次调用它。
export class ProductListComponent implements OnInit {
constructor(private tagService: TagService) { }
ngOnInit(): void {
if (isNullOrUndefined(this.tagService.tagSource.getValue())
this.tagService.getAllTagsByType('user')
}附注:你不需要在你的组件中显式地订阅service observable。相反,您可以使用异步管道直接从服务主体/可观察对象获取数据。
<table *ngIf="tagService.allnormalTags$ | async as allnormalTags">
<tbody>
<tr class="product-list-item" *ngFor="let tag of allnormalTags">
<td data-label="name"> {{tag.name}} </td>https://stackoverflow.com/questions/62542766
复制相似问题