调用.next()后,Angular Observable不会在视图中更新

时间:2019-04-05 06:39:49

标签: angular typescript rxjs observable behaviorsubject

我正在使用Google Maps API验证地址。我有一个服务通过名为 checkDistance()的函数来处理此问题,在该服务中,我创建了一个名为verifyMessage $的可观察对象,以在视图中进行通讯,以了解地址是否有效。

该视图包含一个验证按钮,该按钮调用组件函数 verifyAddress(),然后调用该服务的 checkDistance();

这是问题所在:在我再次单击该页面之前,可观察对象不会使用新值进行更新。我单击验证,然后在控制台中可以看到已经设置了结果,但是“ Loading ...”并没有消失,并且直到我随机单击某处的页面时,verifyMessage的值才会更新。我究竟做错了什么?我该如何解决?

delivery-component.html

     <input formControlName="address" matInput placeholder="Start typing delivery address..." google-place> 
    <button mat-raised-button color="primary" (click)="verifyAddress()" class="col-2">Verify</button>
    <p class="col-12" *ngIf="checkout.verifyMessage$ | async as message; else no message">{{ message.value }}</p>

    <p class="col-12" *ngIf="checkout.loading">Loading...</p>

结帐服务:

  ...

  async checkDistance(location_obj) { 

    this.loading = true; 


    ... Google Maps API stuff ..

          this.result = this.checkValidity(distance);

          console.log('result is: ', this.result);   

          if (this.result) {

            // if valid set this message so can be updated in view

            this.verifyMessage$.next({value: 'Great, that address is in our range.'}); 
            this.loading = false; 
            this.verified=true;

          } else {

            this.verifyMessage$.next({value: 'Uh oh, that address is out of our range. '}); 
            this.loading = false; 
            this.verified=false;
          }
        });
  }

deliveryPrompt.component.ts

import ...

export class DeliveryPromptComponent implements OnInit {

  deliveryAddressForm: FormGroup; 
  message: string; 
  verified$ = new BehaviorSubject({value: false});
  verified = this.verified$.asObservable();

  loading = false; 

  constructor(public dialogRef: MatDialogRef<DeliveryPromptComponent>, @Inject(MAT_DIALOG_DATA) public data: any, public checkout: CheckoutHandlerService,  public fb: FormBuilder, public loginService: AuthService, private cd: ChangeDetectorRef) { 

  }

  ngOnInit() {
    this.checkout.verifyMessage$.subscribe(); 
    this.checkout.verifyMessage.subscribe(); 

    this.deliveryAddressForm = this.fb.group({
      address: ['', [Validators.required]]
    }); 
    this.deliveryAddressForm.valueChanges.subscribe(form => {
      //console.log(form); 
     }); 
     this.message = ''; 
  }

...
  async verifyAddress() {

    console.group('loading 1', this.loading); 
    await this.checkout.checkDistance(this.checkout.tempAddress);  

  }

1 个答案:

答案 0 :(得分:0)

我在使用角度+8时也遇到了类似的问题。当我只使用

ng serve 

角度rxjs没有发送下一个值,但是如果我使用

ng serve --aot=true

有效, 这应该是关于优化的问题。 希望对您有帮助!