ilyablbnv
ilyablbnv

Reputation: 161

Passing JSON Object into Angular 2 Component

I need to pass JSON object from one component to another using RxJS Subject and Observables. Here is my code:

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

save-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() {
    }
}

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

When I am trying to print JSON at the save-form.component - nothing happens. What am I doing wrong? Thanks for the help.

UPDATE: 1) No errors in the console 2) In save-form.component.html I have this:

<div>{{schema | json}}</div>

3) My JSON schema output will look smth like this

{
  "params": [
    {
      "description": "desc1",
      "type": "string"
    }
  ]
}

Upvotes: 4

Views: 2945

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209004

What am I doing wrong?

You are declaring the service in the @Component.providers

@Component({
    providers: [SharedService]
})

This means that you want that component to get its own instance of the service. So when the component is created, a new service will be created.

If you want them to share the same service, then declare the service at the module level

@NgModule({
    providers: [ SharedService ]
})
class AppModule {}

Upvotes: 4

Related Questions