Наблюдаемый неявно отписался в Angular 5 - PullRequest
0 голосов
/ 24 сентября 2018

Я работаю с наблюдаемыми, а моя наблюдаемая отписывается неявно.Но я вообще не хочу отписываться.

Я создал галерею, в которой я отображаю изображения, но есть и другие вкладки.Как вы видите на изображении.

enter image description here

Когда я переключаюсь на какую-то другую вкладку.И переключитесь обратно на вкладку галереи, все изображения исчезли.

вот код

ngOnInit()
  {
    console.log('sp gallery on init');
    // getting images model i.e. id, name desc, content

/****************************This is the observable******************************/

    this.dispImgsSubs = this.galleryService.displayImages.subscribe((displayImages: Array<SPGalleryImagesModel>) =>
    {
      console.log('sp gallery display images on init');

      // adding new images to array
      this.imageModel = this.imageModel.concat(displayImages);

      // re-assigning ids to newest data
      this.imageModel = this.reAssigningIds(this.imageModel, 0);
      console.log(this.imageModel);

      this.isGalleryFromBackend = false;
    });

    if(this.isGalleryFromBackend)
      this.backendService.getSP().subscribe(spData => {

        console.log(spData.locations[0].gallery);
        this.imageModel = spData.locations[0].gallery;
      });
  }

вот сервис галереи

import { Injectable } from '@angular/core';
import { Component, OnInit, ViewChild,  Output, EventEmitter } from '@angular/core';
import { BackendService } from './backend.service';
import { SPGalleryImagesModel } from '../components/models/sp-profile-gallery-images.model';

@Injectable()
export class GalleryService {

  // emit shorten file path to gallery onChange()
  @Output() filename =  new EventEmitter<SPGalleryImagesModel[]>();

  // emit images array to display in gallery ngOnInit()
  @Output() displayImages = new EventEmitter<SPGalleryImagesModel[]>();

  constructor(private backendService: BackendService) { }

  // adding new images
  addImages(newImages)
  {
    console.log('add images');

    // for uploading to server
    let uploadImages = new Array<SPGalleryImagesModel>();

    //iterating through new images array
    for (let i = 0, img; img = newImages[i]; i++)
    {
      let reader = new FileReader();
      let image = new SPGalleryImagesModel();

      image.name = img.name;
      image.index = i;
      // check whether file is of image format
      if(img.type != 'image/jpeg' && img.type != 'image/jpg' && img.type != 'image/png')
        alert('Only images are supported!');
      else
      {
        image.type = img.type
        // getting image base64 string
        reader.onload = () => image.content = reader.result;

        // converting image to base64 string
        reader.readAsDataURL(img);

        uploadImages.push(image);

        // condition applied so that inner statements run only one time
        if(i == newImages.length - 1)
        {
          reader.onloadend = () =>
          {
            // uploading images
            this.uploadBase64(uploadImages);

            // emitting images array to display in gallery
            this.displayImages.emit(uploadImages);
          }
        }
      }
    }
    return false;
  }

  uploadBase64(images: Array<SPGalleryImagesModel>)
  {
    let count: number = 0;

    // to send image shorten path to gallery onChange()
    let imagespath:SPGalleryImagesModel[] = [];

    // iterating image to upload a single instance at a time
    for(let image in images)
    {
      // model for uploading image
      let imageFile = new SPGalleryImagesModel();

      // data to send to gallery onChange()
      let imageData = new SPGalleryImagesModel();

      // adding image data to model
      imageFile.name = images[image].name;
      imageFile.content = images[image].content;
      imageFile.type = images[image].type;
      // uploading image
      console.log('try to upload', imageFile)
      this.backendService.uploadBase64({content:imageFile.content, type: imageFile.type}).subscribe(res =>
      {
        console.log('uploading');

        // getting id and filename (shorten image path)
        imageData.index = +image;
        imageData.filename = res.path;

        // pushing data to array
        imagespath.push(imageData);

        //applying condition so that inner statement executed only once
        if(count == images.length - 1)
          // emitting data (filename, id) to gallery onChange
          this.filename.emit(imagespath);

        count++;
      });
    }
    return false;
  }
}
...