【发布时间】:2020-12-07 12:26:42
【问题描述】:
我有contact-info.service,它可以获取有关页眉和页脚组件的联系人信息。一切正常,但是对于这 1 个 json,BE 收到了 2 个呼叫而不是 1 个呼叫。我如何重构此代码以在后端仅调用 1 次。
所以,contact-info.service.ts:
export class ContactInfoService {
private apiUrl: string;
private endpoint = 'common/main-contact';
constructor(private http: HttpClient) {
this.apiUrl = environment.backendUrl;
}
getContactInformation(): Observable<ContactInfo> {
return this.http.get<ContactInfo>(`${this.apiUrl}/${this.endpoint}`)
.pipe(shareReplay(1));
}
}
header.component.ts :
export class HeaderComponent implements OnInit {
contactInfo$: Observable<ContactInfo>;
constructor(private contactInfoService: ContactInfoService) { }
ngOnInit(): void {
this.contactInfo$ = this.contactInfoService.getContactInformation().pipe(shareReplay(1));
}
}
footer.component.ts:
export class FooterComponent implements OnInit {
currentDate = new Date();
contactInfo$: Observable<ContactInfo>;
constructor(private contactInfoService: ContactInfoService) {}
ngOnInit() {
this.contactInfo$ = this.contactInfoService.getContactInformation().pipe(shareReplay(1));
}
}
【问题讨论】:
-
BE 是什么意思?
-
@FaizalHussain 我假设是“后端”,或者更确切地说是 api
-
是的,就是后端
-
实际上你是从页眉和页脚调用api。最好的方法是从页眉调用 API 并使用行为主题将其传递给页脚
-
@OlehZ 这可能会有所帮助:sharing data between angular components
标签: angular typescript api rest observable