Puneet Sharma
Puneet Sharma

Reputation: 256

how can we send data within modules in Angular 2+

I am stuck on sending some small chunk of data sending from one module to another module. I don't store this chunk of data in query params or in some browser level storage or caching. What options are there for me or does angular has any mechanism to do that without reloading my application.

Upvotes: 1

Views: 758

Answers (2)

Ans Bilal
Ans Bilal

Reputation: 1067

You can create a shared service. Then you can subscribe to that service in both of your modules and share your data.

for example:

this is my http service which is shared between the modules

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { APIUrls } from '../Enums/api-url.enum';
import { HttpResponse } from 'selenium-webdriver/http';
import { SessionStorageService } from './session-storage.service';
import { SessionStorageKeys } from '../Enums/session-storage-keys.enum';

@Injectable()
export class HttpService {

  constructor(private _http: HttpClient, private _sessionService: SessionStorageService) {

  }

  public PostRequest(apiURL: string, body: any): Observable<HttpResponse> {
    let auth_token = this._sessionService.get(SessionStorageKeys.AUTH_TOKEN);
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
      })
    };
    return this._http.post(APIUrls.BaseURL + apiURL, body, httpOptions);
  }

  public GetRequest(apiURL: string): Observable<HttpResponse> {
    let auth_token = this._sessionService.get(SessionStorageKeys.AUTH_TOKEN);
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
      })
    };
    return this._http.get(APIUrls.BaseURL + apiURL, httpOptions);
  }

  private _transformRequest(obj: any): any {
    var str = [];
    for (var p in obj)
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + ":" + encodeURIComponent(obj[p]));
      }
    return str;
  }

}

I added this service in providers array of app.module.ts

then injected this service in constructors of components in different modules

Upvotes: 1

Akshay Rajput
Akshay Rajput

Reputation: 2078

Services are designed for same, (Dependency Injection)

@Injectable()
export class SomeService {
//define a variable
someVariable = "xyz";
}

Provide this service in parent module or root module of the components (app.module.ts)

inject the service in components

one.component.ts
constructor(private someService: SomeService) {

}

// update the variable here

this.someService.someVariable = "Value Changed"

two.component.ts
constructor(private someService: SomeService) {}
// updated variable can be accessed here
console.log(this.someService.someVariable);

Upvotes: 1

Related Questions