问题描述
我有contact-info.service,它获取有关页眉和页脚组件的联系人的信息。一切正常,但是对于这1个json,BE收到了2个呼叫,而不是1个。我如何重构此代码以仅在后端调用一次。
因此, contact-info.service.ts:
export class ContactInfoService {
private apiUrl: string;
private endpoint = 'common/main-contact';
constructor(private http: HttpClient) {
this.apiUrl = environment.backendUrl;
}
getContact@R_131_4045@ion(): 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.getContact@R_131_4045@ion().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.getContact@R_131_4045@ion().pipe(shareReplay(1));
}
}
解决方法
您的服务应如下所示-
export class ContactInfoService implements OnInit {
private apiUrl: string;
private endpoint = 'common/main-contact';
private dataObs;
constructor(private http: HttpClient) {
this.apiUrl = environment.backendUrl;
this.callContactInfo();
}
callContactInfo(){
this.dataObs = this.http.get<ContactInfo>(`${this.apiUrl}/${this.endpoint}`)
.pipe(shareReplay(1));
}
getContactInformation(): Observable<ContactInfo> {
return this.dataObs;
}
}
您可以直接在模板中使用getContactInformation()
,而无需在页眉和页脚中使用pipe(shareReplay(1))
,或者更好的方法是将getContactInformation()
返回的可观察值存储在组件变量中并在您的变量中使用具有异步管道的模板。
我让你有问题...
请顺利检查此代码...
contact-info.service.ts:
import { map } from 'rxjs/operators';
import { Http} from '@angular/http'; //Updated...
export class ContactInfoService {
private apiUrl: string;
public contactInfo = [];
private endpoint = 'common/main-contact';
constructor(private http: Http) {. //Updated...
this.apiUrl = environment.backendUrl;
}
//get request using operaters...
getContactInformation() {
return this.http.get('APIURL').pipe(map((response: any) =>response.json()));
}
getContactInformation(): Observable<ContactInfo> {
return this.http.get<ContactInfo> (`${this.apiUrl}/${this.endpoint}`)
.pipe(shareReplay(1));
}
setContactInfo(data) {
this.contactInfo = data;
}
getContactInfo() {
return this.contactInfo;
}
}
header.component.ts:
ngOnInit() {
this.contactInfoService.getContactInformation().subscribe((res) => {
this.contactInfoService.setContactInfo(res);
}
}
footer.component.ts:
ngOnInit() {
let contactData = this.contactInfoService.getContactInfo()
consolo.log(contactData)
}
}
现在您可以在整个项目中使用this.contactInfoService.getContactInfo()
来获取contactInfo了!
和它只会一次将请求发送到服务器
让我知道是否有帮助!