定义可观察接口

Define Interface for observable

我在 angular component.ts 文件中有一个函数,例如

createOrUpdateAlertingProfile() {

**let request: Observable<any>;**
let successMessage: string;

if (!this.alertingProfile) {
  const slackConfigurationIdvalue = this.createOrEditAlertingProfileForm.get('slackConfigurationId').value;
  const organizationIdvalue = this.createOrEditAlertingProfileForm.get('organizationId').value;
  const remiderValue = this.createOrEditAlertingProfileForm.get('reminder').value;
  const newAlertingProfileValue: AlertingProfileCreation = {
    ...this.createOrEditAlertingProfileForm.value,
    slackConfigurationId: slackConfigurationIdvalue === '' ? undefined : slackConfigurationIdvalue,
    organizationId: organizationIdvalue === '' ? undefined : organizationIdvalue,
    reminder: remiderValue === '' ? undefined : remiderValue,
    emails: this.emails.length === 0 ? undefined : this.emails.value,
    webhooks: this.webhooks.length === 0 ? undefined : this.webhooks.value,
  };
  request = this.alertingProfilesService.createAlertingProfile(newAlertingProfileValue);
  successMessage = 'New alerting profile was successfully added';
}

if (this.alertingProfile) {
  request = this.alertingProfilesService.updateAlertingProfile(this.createOrEditAlertingProfileForm.value);
  successMessage = `Alerting profile ${this.alertingProfile.name} was updated`;
}

request.subscribe(
  () => {
    this.alertify.success(successMessage);
    this.isLoading$.next(false);
    this.dialogRef.close(true);
  },
  (error) => {
    this.alertify.error('\n' + error);
    this.isLoading$.next(false);
  },
 );
}

'request' 是可观察类型

请求调用两个服务之一

createAlertingProfile(newAlertingProfile: AlertingProfileCreation) {
 return this.http.post(`${this.baseUrl}/create`, newAlertingProfile);
}

updateAlertingProfile(model: AlertingProfileUpdate) {
 return this.http.post(`${this.baseUrl}/edit`, model);
}

使用的两个接口'AlertingProfileCreation'和'AlertingProfileUpdate'

export interface AlertingProfileUpdate {
 name: string;
 slackConfigurationId: number;
 organizationId: number;
 reminder: number;}

export interface AlertingProfileCreation {
 name: string;
 slackConfigurationId: number;
 organizationId: number;
 emails: AlertingProfileEmail[];
 webhooks: Webhook[];
 reminder: number;}

我的问题是我想为可观察的请求定义类型,当我尝试时

let request: Observable<AlertingProfileUpdate | AlertingProfileCreation>

它会抛出错误,我该如何为 Observable 定义接口?

您可以使用 Observable<AlertingProfileUpdate> | Observable<AlertingProfileCreation> 但请记住,您将只能访问两个接口的交叉部分(以类型安全的方式来说)

TS playground

此外,请记住,您也应该投射您的 http 调用。

createAlertingProfile(newAlertingProfile: AlertingProfileCreation):Observable<ReturnTypeOfCreation> {
 return this.http.post<ReturnTypeOfCreation>(`${this.baseUrl}/create`, newAlertingProfile);
}

updateAlertingProfile(model: AlertingProfileUpdate):Observable<ReturnTypeOfUpdate> {
 return this.http.post<ReturnTypeOfUpdate>(`${this.baseUrl}/edit`, model);
}