【问题标题】:Inject data from service to component将数据从服务注入到组件
【发布时间】:2018-11-27 10:23:31
【问题描述】:

目前,我正在使用 Rx.JS 和 Angular 7。我的问题与 Observable 中的问题有关。

问题是我无法从服务中获取数据到 form-code.component

在我使用 setShortCode() 后,有数据,但在 form-code.component.ts 我看不到 seebscribe() 数据

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();
  }
}

【问题讨论】:

  • 以null为初始值更改行为主题
  • 谢谢你,范!非常有用的信息!

标签: javascript angular rxjs observable angular6


【解决方案1】:

工作,当我将主题更改为 BehaviorSubject 时

【讨论】:

    猜你喜欢
    • 2016-02-10
    • 2020-06-08
    • 2017-05-06
    • 2018-08-22
    • 2018-05-20
    • 2011-01-03
    • 2018-06-30
    • 2019-12-09
    相关资源
    最近更新 更多