0

Как решить проблему переподписки при переключении на другую страницу:

export class NewsService {
  newsCollection: AngularFirestoreCollection < News > ;
  newsArr: Observable < News[] > ;

  constructor(private readonly afs: AngularFirestore) {
    // this.newsArr = this.afs.collection('news').valueChanges();
    this.newsCollection = this.afs.collection('news', ref => ref.orderBy('date', 'desc'));

    this.newsArr = this.newsCollection.stateChanges().map(changes => {
      return changes.map(a => {
        const data = a.payload.doc.data() as News;
        data.id = a.payload.doc.id;
        return data;
      });
    });
  }

  getNews() {
    return this.newsArr;
  }
  addItem(news: News) {
    this.newsCollection.add(news);
  }
}

компонент

 newsArr: News[];
  constructor(private newsService: NewsService) { }

  ngOnInit() {
    this.newsService.getNews().subscribe(newsArr => {
      this.newsArr = newsArr;
    });
  }

1 ответ 1

0

Невнимательность и усталость приводят к тяжким последствиям((( решение этой проблемы я написал сам жалко только в другом компоненте... но на заметку если кто столкнется...

import {Component, OnDestroy, OnInit} from '@angular/core';
import {NewsService} from '../../service/news.service';
import {News} from '../../modules/news';
import {Subscription} from 'rxjs/Subscription';

@Component({
  moduleId: module.id,
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit, OnDestroy {
  newsArr: News[];
  newsSub: Subscription;
  constructor(private newsService: NewsService) { }

  ngOnInit() {
    this.newsSub = this.newsService.getNews().subscribe(newsArr => {
      this.newsArr = newsArr;
    });
  }
  ngOnDestroy() {
    this.newsSub.unsubscribe();
  }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.