当前,我正在使用Rx.JS和Angular7。我的问题涉及Observable中的问题。
问题是我无法从服务获取数据到 form-code.component 。
在我使用了 setShortCode()之后,有setset数据,但是在 form-code.component.ts 中,我看不到 seebscribe()< / strong>数据
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();
}
}
答案 0 :(得分:1)
工作,当我将“主题”更改为“ BehaviorSubject”