Communicating between two Angular 2 components by passing an object through a service

I am currently developing an Angular 2 beta9 application where I am trying to establish communication between two components. I have a "start" component that consists of a radio box button, and the selected item is supposed to be transferred as an object via a service to the "destination" component. The "destination" component will then use this selected item to filter the data it uses.

The issue I'm facing is with passing the object from the "start" component to the service:

FormeService.ts:44 
Object {id: 1, submenu: "type1", nb: 102, value: "Porte Fenêtre", class: ""…}

However, when trying to pass the object from the service to the "destination" component, the object appears as undefined: undefined

This is my code:

Start component:

@Component({
    selector: 'radioFormesType1',
    templateUrl: 'component1.html',
    styleUrls: ['component1.css'],

    directives: [MATERIAL_DIRECTIVES]

})
export class RadioFormesType1Component implements OnInit, OnDestroy{

    // Initial value for the radio box
    data: any = {init: 'Fenêtre'};

    // List parsed from the service
    items_list;

    constructor(public formeService: FormeService) {}

    ngOnInit(){
        this.formeService.getjson().subscribe(people => this.items_list = people);
    }

    ngOnDestroy(){}

    public onSelectType1(selected:any){
        console.log("Selected value: "+selected.value);
        this.formeService.changeForme(selected);
        console.log("Selected value passed to service: "+selected.value);
    }
}

The action of clicking is triggered by onSelectType1():

<div *ngFor="#item of items_list">
            <md-radio-button
                    *ngIf="item.id===1"
                    value="{{item.value}}"
                    class="{{item.class}}"
                    checked="{{item.checked}}"
                    (click)="onSelectType1(item)">
                {{item.label}}
            </md-radio-button>
        </div>
    </md-radio-group>

The service acquires this object and places it in a new object named "type1". Here is the code of my service loading JSON data by default:

import {Injectable,EventEmitter,Output} from 'angular2/core';
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';

@Injectable()
export class FormeService{

    private _type1:any;

    get type1():any {
        return this._type1;
    }

    set type1(value:any) {
        this._type1 = value;
    }

    constructor (public http : Http){
        this.http= http;
    }

    getjson(){
        return this.http.get('dev/JsonData/formes.json')
            .map(res => res.json())
    }

    public changeForme(selected):any{
        console.log(selected);

        this._type1=selected
        console.log("Service storing type1 value: "+this._type1);

        return this._type1;
    }

Lastly, in the "destination component," the object seems to be undefined at this level when placed in a new object named type1Recu:

@Component({
    selector: 'checkboxFormesType2',
    templateUrl: 'component2.html',
    styleUrls: ['component2.css'],
    directives: [MATERIAL_DIRECTIVES,RadioFormesType1Component]
})
export  class CheckboxFormesType2 {

    items_list;
    public type1Recu: any;

    constructor(public formeService: FormeService) {
        this.type1Recu = this.formeService.type1 ;
        console.log(this.formeService.type1)
    }

    ngOnInit(){
        this.formeService.getjson().subscribe(people => this.items_list = people);
    }

    ngOnDestroy(){}

Any suggestions on how to successfully load the complete object in the destination component?

Answer №1

It's difficult to determine without seeing the code where CheckboxFormesType2 is being used. However, it appears that you may be initializing CheckboxFormesType2 before defining type1, possibly before selecting a radio checkbox. To resolve this issue, consider adding an *ngIf=type1" attribute to your CheckboxFormesType2:

<checkboxFormesType2 *ngIf="type1"></checkboxFormesType2>

This will prevent CheckboxFormesType2 from being created until type1 has been defined.

Regarding service communication, it might be more effective to utilize a subject in your service. Consider implementing it as follows:

FormeService:

import {Injectable,EventEmitter,Output} from 'angular2/core';
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';
import {Subject} from 'rxjs/Rx';

@Injectable()
export class FormeService{
    public type1 = new Subject();
...
}

In RadioFormesType1Component:

export class RadioFormesType1Component implements OnInit, OnDestroy{
    ...
    public onSelectType1(selected:any){
        this.formeService.type1.next(selected);
    }
    ...
}

In CheckboxFormesType2:

export  class CheckboxFormesType2 {
    ...
    type1Recu:any;
    constructor(public formeService: FormeService) {
        this.formeService.type1.subscribe( type1 => this.type1Recu = type1);
    }
    ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement the addition of subcollections to a unified identification document in Firestore

I am struggling to store the URLs of multiple images (previously saved in Storage) in a subcollection of a Firestore document. Although I have managed to do it, each image generates a new document with its corresponding sub collection img, which is not my ...

Angular2: Ensuring Sequential Execution Line by Line - A Comprehensive Guide

I have a designed an Angular2 Navbar Component that features a logout button: import { Component, OnInit } from '@angular/core'; import { LoginService } from '../login.service'; import { Router } from '@angular/router'; @Co ...

Updating CSS classes based on conditions in Angular 2

I have a view with three buttons, and initially the content of the first button is displayed. When a button is clicked, it becomes active, but on page load, the initial button does not have the active state. To set the first button as active upon page load ...

Issue with Angular2 formBuilder: two validators are not functioning as expected

Need help with a text input that is required and must be longer than 3 characters. When clicking on the input, if a user types something shorter than 3 characters and then clicks out, a red border should be added. Otherwise, the border should be green. ...

Effortless method for combining PHP API with Angular 2 application on your computer

Currently, I am developing a new Angular 2 application that interacts with a REST API built on PHP. To simulate the data flow, I have generated mock data in a json file for the front end. The PHP REST API was created using MAMP and has been tested succes ...

Ways to access information from a SQLite database using Angular

I am a beginner in front-end/back-end communication and I need guidance on how to retrieve data from a SQLite db file to populate a page in my Angular project. I have no idea where to begin, so any resources you can recommend would be greatly appreciated. ...

What are the steps to establishing a Vue 3 TypeScript Plugin?

I am currently in the process of developing a new Plugin for Vue 3 using Typescript. Here is an overview of my code: //somePlugin import { App, Plugin } from "vue"; const somePlugin: Plugin = { install: async (app: App, options: {...}): Promi ...

Tips for creating dynamic amd-dependencies in TypeScript

Is there a way to dynamically load a Javascript language bundle file in Typescript based on the current language without using static methods? I want to avoid having to use comments like this for each bundle: /// <amd-dependency path="<path_to_bund ...

Implementing setDoc with Firebase-Admin using Typescript in Firestore

I'm having issues with my code in config/firebase.ts: import { initializeApp, cert } from 'firebase-admin/app'; import { getFirestore } from 'firebase-admin/firestore' const firebaseAdminApp = initializeApp({ credential: cert( ...

Do you find this unattractive? What are some ways to improve this unsightly JavaScript statement?

This code seems messy, how can I better structure this switch statement? function renderDataTypeIcon(dataType: string) { let iconName; switch (dataType) { case "STRING": //TODO - ENUM iconName = "text"; break; ...

What is the best way to incorporate sturdy data types into the alternative function for this switch statement

const switchcase = (value, cases, defaultCase) => { const valueString = String(value); const result = Object.keys(cases).includes(valueString) ? cases[valueString] : defaultCase; return typeof result === 'function' ? result() : r ...

Issue with Angular 4: Module not found after creation

Recently, I created a basic module using ng called "core" in my app folder. It is located at the same level as app.module. However, when I attempt to utilize it from app.module.ts, I encounter an error stating 'Cannot find module' import { CoreM ...

angular missing module for highcharts geo heatmap

I am completely new to HighCharts and just starting out with it. My current challenge involves creating a geo-heatmap using HighCharts within an Angular environment. Despite my efforts in researching through Google, I managed to put together a chart but en ...

Cypress is unable to drag a customized angular cdkDragHandle functionality

My mind is unraveling due to this issue. I have a drag and drop list in my application with a customized drag handle, but Cypress seems incapable of dragging it. When manually dragged by the user, everything works flawlessly. Below is the simple component ...

Determine parameter types and return values by analyzing the generic interface

I am currently working on a feature where I need to create a function that takes an interface as input and automatically determines the return types based on the 'key' provided in the options object passed to the function. Here is an example of ...

Experiencing difficulties while trying to showcase a PDF within the Expo Go app

I am currently developing a React Native application that requires the display of PDF files. I have tried two different methods, one using react-native-webview and the other with react-native-pdf, but both approaches are presenting challenges. This is how ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

Utilizing Carousel Functionality in Angular 4

I've added a Carousel to one of my components. Bootstrap has been correctly imported (verified by testing a bootstrap button). The active image, slider icons, and navigation icons at the bottom are all visible. However, the images are not sliding and ...

Turning an array of strings into a multidimensional array

I have a JavaScript string array that I need to convert into a multidimensional array: const names = [ "local://john/doe/blog", "local://jane/smith/portfolio", "as://alexander/wong/resume" ]; The desired output sh ...

Incorporate the move_uploaded_file() function into your PHP code to manipulate JSON data

When I receive the data through an Angular JSON request, it comes in a format that doesn't include ($_FILES['name']['tmp_name']), so I am unable to use move_uploaded_file() Web JSON Data avatar { contentType "application/pdf ...