可观察的取消订阅方法不可用

时间:2020-03-04 20:05:15

标签: angular typescript ngrx-store

我正在尝试退订ngOnDestroy

  ngOnDestroy(): void {
    this.user.unsubscribe()
  }

可观察类型

不存在退订

我正在使用loginUser函数的方法

  loginUser(): void {
    const raw = this.userForm.getRawValue();
    let post = {
      username: raw.username,
      password: raw.password
    };
    console.log(post);
    this.user.subscribe(err => {
      this.error = err;
    });
    this.store.dispatch(new initLogin(post));
  }

loginComponent(完整代码)

import { Component, OnInit, DoCheck, OnDestroy } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { initLogin } from "../../../store/actions/auth.actions";
import { Store, select } from "@ngrx/store";
import { State, loginError } from "../../../store/reducers";
import { Observable, from } from "rxjs";

@Component({
  selector: "app-login-form",
  templateUrl: "./login-form.component.html",
  styleUrls: ["./login-form.component.css"]
})
export class LoginFormComponent implements OnInit, OnDestroy {
  userForm: FormGroup;
  username: string;
  password: string;
  user: Observable<any>;
  error: Observable<any>;
  isAuthenticated: Observable<boolean>;

  constructor(private store: Store<State>) {}

  ngOnInit(): void {
    this.userForm = new FormGroup({
      username: new FormControl(""),
      password: new FormControl("")
    });
    this.user = this.store.pipe(select(loginError));
  }
  // can handle validations
  loginUser(): void {
    const raw = this.userForm.getRawValue();
    let post = {
      username: raw.username,
      password: raw.password
    };
    console.log(post);
    this.user.subscribe(err => {
      this.error = err;
    });
    this.store.dispatch(new initLogin(post));
  }
  ngOnDestroy(): void {
    this.user.unsubscribe()
  }
}

1 个答案:

答案 0 :(得分:2)

您必须将订阅分配给变量。

尝试:

import { Subscription } from 'rxjs';
.....
userSubscription: Subscription;

...
this.userSubscription = this.user.subscribe(err => {
      if (this) {
        this.error = err;
      }
    });

ngOnDestroy(): void {
    this.userSubscription.unsubscribe();
  }