Inject data from service to component

Currently, I'm using Rx.JS and Angular 7. My problem contains with the issue in Observable.

The problem is I can't fetch data from service to form-code.component.

After I've used setShortCode() there isset data, but in form-code.component.ts i can't see seebscribe() data

shortcode.service.ts

import { Injectable, NgZone } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ShortcodeService {
  public shortcode = new Subject<any>();
  constructor(private zone: NgZone) {}

  setShortCode(code) {
    this.zone.run(() => {
      this.shortcode.next(code);
    });
  }

  getShortCode(): Observable<any> {
    return this.shortcode.asObservable();
  }
}

dnd.component.ts

this.textAreaText = `<iframe src="${window.location.origin +
          '/form/' +
          project.id}/design" width="100%" height="500px" frameborder="0"></iframe>`;
        this.shortCodeService.setShortCode(this.textAreaText);
        this.router.navigate(['/form-copy']);

form-code.components.ts

import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { ShortcodeService } from '../../services/shortcode.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-form-code',
  templateUrl: './form-code.component.html',
  styleUrls: ['./form-code.component.scss']
})
export class FormCodeComponent implements OnInit, OnDestroy {
  constructor(
    private sanitizer: DomSanitizer,
    private shortCodeService: ShortcodeService
  ) {}
  shortText: string;
  sub: Subscription;
  ngOnInit() {
    this.sub = this.shortCodeService.getShortCode().subscribe(
      shortcode => {
        console.log(shortcode);
        this.shortText = shortcode;
      },
      error => console.log(error),
      () => {}
    );
  }

  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    this.sub.unsubscribe();
  }
}

Upvotes: 0

Views: 144

Answers (1)

Working, When I changed Subject to BehaviorSubject

Upvotes: 1

Related Questions