简体   繁体   中英

How to run function only when service variable state changed in component Angular4

I have service called as InfoFormService and it has a variable called isInValidating.

The variable is set as true when component invoke validateEmail(email) function as below.

@Injectable()
export class InfoFormService {

    private VALIDATE_EMAIL_URL: string = 'XXX';
    isInValidating: boolean = false;

    constructor(@Inject(APP_CONFIG) private config: AppConfig,
                private http:Http
    ) {

      console.log(this.config.apiEndpoint)

    }

    validateEmail(email) {
      console.log(email)
      this.isInValidating = true;
      return this.http.get(`${this.config.apiEndpoint}/${this.VALIDATE_EMAIL_URL}${email}`)
    }

}

And the component invoke validateEmail whenever email input text changed.

Because ValidateEmail takes time, when I click submit button, the isInValidating value might be true or false, but once ValidateEmail action completed, the isInValidating value will set as false as above code.

What I want is to delay submit action which happens when click Submit button until service's isInValidating value set as true.

export class AbcBtnComponent implements OnInit {

    constructor(private formService:InfoFormService) {

    }

    ...

    emailField.valueChanges
      .filter(val => {
        return val.length >= 1;
      })
      .debounceTime(100)
      .switchMap(val => this.formService.validateEmail(val))
      .subscribe(res => {

        console.log(res)
        let validation = res.json();

        if (validation['valid']) {
          emailField.setErrors(null);
        } else {
          emailField.setErrors({ validEmail: true });
        }

        this.formService.isInValidating = false;

      });

    onSubmit(value) {
        // Here I want to delay until formService's isInValidating value = true

        submitAction(value)
    }

}

I guess that I have to use Subject or Observable, but have no idea how to use it.

Please help me!

In component

get isInValidating(): boolean {
    return this.formService.isInValidating;
}

In template

<button type="submit" [disabled]="isInValidating">Submit</button>
this.formService.validateEmail(val))
      .subscribe(res => {

this.formService.validateEmail(val)
      .subscribe(res => {
..)

Technically if you subscribe to the validateEmail call and execute your code there, it should work. But I might have missunderstood your question.

You could also just remove the isInValidating and have the onSubmit(value) inside like:

this.formService.validateEmail(val)).subscribe(res => {
//logic to check your validation
if(valid) this.onSubmit(val)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM