来回更改路由后,可观察的数据消失了

时间:2018-08-15 16:45:40

标签: angular typescript firebase rxjs angularfire

我一直在开发Angular应用程序。我有一个events.service,其中包含方法getEvents(),该方法从我拥有的Angular Firestore集合中返回类型为Event的Observable。

在我的homepage.component中,我的getEvents()方法订阅了事件集合的valueChanges(),该事件集合将集合存储到我的数组Event的本地变量中。

现在,它可以很好地工作,并且订阅也完美无缺。我在Firestore中添加,修改或删除的所有文档都会在我的客户端中实时更新。很酷的东西。

问题是当我路由到另一个页面,然后导航回到我的主页时,我的本地变量为空!我不知道为什么。

这是我的代码:

app.module.ts

const appRoutes: Routes = [
    { path: "", redirectTo: "/login", pathMatch: "full" },
    { path: "login", component: LoginComponent },
    { path: "signup", component: SignupComponent },
    { path: "home", component: HomepageComponent, canActivate: [AuthGuard] },
    {
      path: "reservepage/:id",
      component: ReservePageComponent
    },
    { path: "scan", component: ScanPageComponent },
    { path: "create", component: CreateEventPageComponent },
    { path: "preview/:id", component: PreviewEventPageComponent }
  ];

event.service.ts

    // Angular imports
    import { Injectable } from "@angular/core";

    // Angular Fire Imports
    import {
      AngularFirestore,
      AngularFirestoreCollection,
      AngularFirestoreDocument,
      fromDocRef
    } from "angularfire2/firestore";
    import { AngularFireAuth } from "angularfire2/auth";
    import * as firebase from "firebase";

    // Internal imports
    import { Event } from "./event";
    import { AuthService } from "../auth/auth.service";

    // rxjs imports
    import { Observable, of } from "rxjs";
    import { map } from "rxjs/operators";

    @Injectable({
      providedIn: "root"
    })
    export class EventsService {
      constructor(
        private angularFirestore: AngularFirestore,
        private authService: AuthService,
        private firebaseAuth: AngularFireAuth
      ) {}

      collection: AngularFirestoreCollection<
        Event
      > = this.angularFirestore.collection("events");
      collection$: Observable<Event[]> = this.collection.valueChanges();

      document: AngularFirestoreDocument<Event>;
      document$: Observable<Event>;

      id: string;

      add(
        _name: string,
        _description: string,
        _photoURL: string,
        _address?: string,
        _totalTickets?: number,
        _ticketsSold?: number,
        _ticketsAvailable?: number
      ) {
        this.collection
          .add({
            id: "",
            name: _name,
            description: _description,
            photoURL: _photoURL,
            uid: this.firebaseAuth.auth.currentUser.uid,
            address: _address,
            totalTickets: _totalTickets
          })
          .then(docRef => {
            this.collection.doc(docRef.id).update({
              id: docRef.id
            });
            this.setId(docRef.id);
          });
      }

      getEvents(): Observable<Event[]> {
        return this.collection$;
      }

      getEvent(id: string): Observable<Event> {
        // return a document as a type
        this.document = this.collection.doc(id);
        this.document$ = this.document.valueChanges();
        return this.document$;
      }

      setId(id: string) {
        this.id = id;
      }

      getId() {
        return this.id;
      }
    }

homepage.component.ts

// Angular Imports
import { Component, OnInit } from "@angular/core";

// Internal Imports
import { AuthService } from "../../auth/auth.service";
import { NavbarComponent } from "../../components/navbar/navbar.component";
import { EventCardComponent } from "../../components/event-card/event-card.component";
import { Event } from "../../event/event";
import { EventsService } from "../../event/events.service";

// AngularFire imports
import { AngularFirestore } from "angularfire2/firestore";

// rxjs imports
import { Observable } from "rxjs";

// firebase
import * as firebase from "firebase";

@Component({
  selector: "app-homepage",
  templateUrl: "./homepage.component.html",
  styleUrls: ["./homepage.component.css"]
})
export class HomepageComponent implements OnInit {
  constructor(
    private authService: AuthService,
    private eventsService: EventsService,
    private afs: AngularFirestore // public navbar: NavbarComponent
  ) {}

  events: Event[] = [];
  myEvents: Event[] = [];

  eventsFilled: boolean;

  getEvents(): void {
    this.eventsService.getEvents().subscribe(events => {
      this.events = events;
      console.log("the length of the events pulled are: " + this.events.length);
    });
  }

  ngOnInit() {
    this.getEvents();
    console.log(
      "the length of the events logged from onInit are: " + this.events.length
    );
  }
}

2 个答案:

答案 0 :(得分:3)

您是否在组件中引用局部变量?

如果是这样,当您离开某个组件时,该组件将被销毁。它在任何属性(局部变量)中具有的任何状态都消失了。您不能在路由之间的组件中保留状态。

相反,您可以将该状态存储在服务中。如果您向根应用程序注入程序注册服务,那么即使该组件被破坏,该服务也将保留。

答案 1 :(得分:0)

我相信是因为您在组件中拥有订阅,所以在导航组件时,组件可能会被破坏(取决于您对路线的管理方式),如果那样,那么每次都会创建订阅