在http错误响应后,将输入角度设置为错误状态

时间:2019-02-08 12:37:54

标签: angular angular-material

是否有可能在http错误响应后将mat-input设置为错误状态?从下面的代码提交表单后,即时消息发送了一个http请求,我想显示mat-error,但仅在输入处于错误状态并且错误响应后我不知道如何将其设置为“ manualy”时显示

<form [formGroup]="exampleForm" (ngSubmit)="onSubmit()">
  <mat-form-field>
    <input matInput placeholder="placeholder" formControlName="Input" required>
    <mat-error *ngIf="variable">error message</mat-error>
  </mat-form-field>
</form>

1 个答案:

答案 0 :(得分:0)

serviceClass:

export class serviceClass{
    private url: string = 'your url'// your http request url

    constructor(private http: HttpClient) { }

    callApi() {
        return this.http.get(this.url);
    }
}

componentClass:在订阅http请求(如果您收到响应错误)时可以将errorVariable设置为true。

export class componentClass{
        private url: string = 'your url'
        public errorVariable:boolean;
        constructor(private service: serviceClass) { }

        getApi() {
            return this.service.callApi().subscribe(
              (response:string)=>{
                console.log(response);
             },
            (error)=>{
                console.error(error);
                this.errorVariable=true;
            }
            );
        }
    }

html模板:

<mat-error *ngIf="errorVariable">error message</mat-error>