【发布时间】:2023-01-11 09:22:32
【问题描述】:
我正在努力做到这一点,以便我的屏幕在我进行预订(按下按钮时创建)后更新预订,但我似乎无法在按下按钮后进行更新
新保留组件.html
<button (click)="onButtonClick()" mat-raised-button class="btn btn-primary" >Create</button>
新保留组件.ts
private scheduleComponent: ScheduleComponent
onButtonClick() {
this.scheduleComponent.ngOnInit()
//also tried calling the other functions by making them public like fetchReservation
}
计划组件.ts
import {
Component,
OnDestroy,
OnInit
} from '@angular/core';
import {Reservation} from "../../reservation.model";
import {ReservationsHttpService} from "../../reservations-http.service";
import {Subscription} from "rxjs";
import {HttpClient} from "@angular/common/http";
@Component({
selector: 'app-schedule',
templateUrl: './schedule.component.html',
styleUrls: ['./schedule.component.scss']
})
export class ScheduleComponent implements OnInit, OnDestroy {
isFetching = false;
error: any = null
private errorSub: Subscription;
reservations: Reservation[] = [];
weekYear_ReservationMap: Map<string, Reservation[]> = new Map<string, Reservation[]>();
constructor(private http: HttpClient, private reservationHttpService: ReservationsHttpService) {
}
ngOnInit(): void {
this.errorSub = this.reservationHttpService.error.subscribe(errorMessage => {
this.error = errorMessage;
});
this.fetchReservations();
}
ngOnDestroy() {
this.errorSub.unsubscribe();
}
private mapReservationsToWeekYear(): Map<string, Reservation[]> {
let reservationMap = new Map<string, Reservation[]>();
for (let reservation of this.reservations.sort((a, b) => a.date > b.date ? 1 : -1)) {
let isWeekOfNextYear = ( reservation.date.getMonth() + 1 == 12
&& reservation.getWeekNumber() == 1); // To group according to ISO 8601.
// curMonthYearKey is also the header displayed in the template.
let curMonthYearKey = (reservation.date.getFullYear() + (isWeekOfNextYear ? 1 : 0)) + " - Week: " + reservation.getWeekNumber();
let curMonthYearArray = reservationMap.get(curMonthYearKey) || [];
curMonthYearArray.push(reservation);
reservationMap.set(curMonthYearKey, curMonthYearArray || []);
}
return reservationMap;
}
private fetchReservations(){
this.isFetching = true;
this.reservationHttpService.fetchOpenReservations()
.subscribe((reservations) => {
this.reservations = reservations;
this.weekYear_ReservationMap = this.mapReservationsToWeekYear();
this.isFetching = false;
}, (error) => {
this.error = error;
this.isFetching = false;
}
)
}
}
我尝试创建一个属性来使用 schedule component.ts 的功能,但它不起作用,我还尝试将 OnInit 更改为 DoCheck、OnChanges、OnViewChanges 等,但这也不起作用(或者确实起作用但发送太多请求导致我的网站崩溃,比如当我尝试 DoCheck 或 AfterContentChecked 时)
我也试过做 @ViewChild(ScheduleComponent) scheduleComponent:ScheduleComponent; 然后做 this.scheduleComponent.ngOnInit() 但这也行不通
【问题讨论】:
-
手动调用
ngOnInit似乎很奇怪,但它没有触发的原因是因为你遗漏了():(click)="onButtonClick()" -
我改变了,谢谢但是现在我收到“无法读取未定义的属性(读取'ngOnInit')”错误消息
标签: angular typescript function components