Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - How to share an app variable with all components

Tags:

angular

I am making a small application with Angular7 on Front and Flask on Back, what i am tryig to do is to subscribe for a service then to save the returned data into an object type variable from inside my main AppComponent, then to access this varialbe in all my other components.

Api service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  CheckApi(){
    return this.http.get('http://localhost:5000/')
  }

}

AppComponent

import { Component, OnInit, Injectable } from '@angular/core';
import { ApiService } from './api.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  title = 'Inbox App';

  public text: object

  constructor(private data: ApiService){}

  ngOnInit(){
    this.data.CheckApi().subscribe(data => {
        this.text = data
        console.log(this.text)
    })
  }
}

And here is where i am trying to access that object from within another component:

LoginComponent

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

login.component.html

<section>
    <legend class="text-center">{{ text }}</legend>
</section>
like image 564
swordfish Avatar asked Oct 17 '22 05:10

swordfish


2 Answers

This can be done several way. Best is to use angular input

import { Component, OnInit, Input } from '@angular/core';

@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
@Input() text: string; 
constructor() { }

ngOnInit() {
}

}

Then you can pass variable from parent component to child component like this

<app-login text="yourvariable or object"></app-login>
like image 136
Manzurul Avatar answered Nov 15 '22 09:11

Manzurul


I have created service for this purpose in my project which saves all data I want in objects property. And then it's possible to access it from everywhere in the project.

import {Injectable} from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataStorage {
  private dataStorage = {};

  addData(key: string, data: any) {
    this.dataStorage[key] = data;
  }

  getData(key: string) {
    this.changed[key] = false;
    return this.dataStorage[key];
  }

  clearData(key: string) {
    this.dataStorage[key] = undefined;
  }
}
like image 32
Josef Katič Avatar answered Nov 15 '22 10:11

Josef Katič