簡體   English   中英

將數據從服務注入到組件

[英]Inject data from service to component

當前,我正在使用Rx.JS和Angular7。我的問題包含在Observable中。

問題是我無法從服務獲取數據到form-code.component

在我使用setShortCode()之后,有isset數據,但是在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']); 

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

工作,當我將“行為主體”更改為“主題”時

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM