我需要使用Subject RxJS和Observables将json obj从一个组件传递到另一个组件。这里是我的代码:将JSON对象传递到Angular 2组件
元form.component.ts
import { SharedService } from "../../../shared/shared.service";
@Component({
selector: 'meta-form',
template: require("./meta-form.component.html"),
styles: [require("./meta-form.component.css")],
providers: [SharedService]
})
export class MetaFormComponent implements OnInit {
public metaForm: FormGroup;
constructor(private _fb: FormBuilder, private sharedService: SharedService) { }
ngOnInit() {
this.metaForm = this._fb.group({
params: this._fb.array([
this.initParam(),
])
})
}
initParam(): any {
return this._fb.group({
description: ['', Validators.required],
type: ['', Validators.required]
})
}
sendJSON() {
let json = JSON.stringify(this.metaForm.value);
this.sharedService.MetaData(json);
}
}
保存-form.component
import { SharedService } from "../../../shared/shared.service";
import 'rxjs/Rx';
@Component({
selector: 'save-form',
template: require("./save-form.component.html"),
styles: [require("./save-form.component.css")],
providers: [SharedService]
})
export class SaveFormComponent implements OnInit {
schema: string[];
constructor(private sharedService: SharedService) {
sharedService.metaData$.subscribe((res) => this.schema = res);
}
ngOnInit() {
}
}
和shared.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SharedService {
private metaData = new Subject<string[]>();
metaData$ = this.metaData.asObservable();
MetaData(jsonData) {
this.metaData.next(jsonData);
}
}
当我我试图在save-form.component中打印json - 没有任何反应。我究竟做错了什么?谢谢您的帮助。
UPDATE: 1)在控制台中没有错误 2)在保存-form.component.html我有这样的:
<div>{{schema | json}}</div>
3)我的JSON模式输出看起来水木清华这样
{
"params": [
{
"description": "desc1",
"type": "string"
}
]
}
声明服务有没有在日志中的任何错误?另外,你可以包括你如何试图打印JSON以及JSON实际采用什么形式的例子吗? – silentsod
@silentsod已更新 – ilyablbnv
在'SaveComponent'中,'schema'确实是一个字符串数组,还是应该只是一个字符串?它看起来像observable只是推出一个字符串。 –