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>
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>
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With