angular2 sharing data between components , getters and setters [duplicate] - javascript

This question already has answers here:
Angular2 - Share data between components using services
(3 answers)
Closed 5 years ago.
I have a question identical to this guy here:
Angular 2 Setter and Getter
The solution que provided thought is not enough for my project to work so I'll explain my situation with some more details to see if you guys can help me!
I have a service dataBase.service.ts :
import {Injectable} from "#angular/core";
#Injectable()
export class dataBaseService{
serviceData: string;
get data():string{
return this.serviceData;
}
set data(value:string){
this.serviceData = value;
}
}
this service is obviously added to app.module.ts as a provider..
on my component A i have:
import { Component, OnInit } from '#angular/core';
import {dataBaseService} from "../dataBase.service";
#Component({
selector: 'app-tipo',
templateUrl: './tipo.component.html',
styleUrls: ['./tipo.component.scss'],
providers: [dataBaseService]
})
export class A implements OnInit {
constructor( public dataService:dataBaseService) {
this.dataService.serviceData = 'hello';
}
ngOnInit() {
console.log(this.dataService.serviceData);
}
}
Until Here everything is fine. If I show on console:
console.log(this.dataService.serviceData); it returns me "hello" as expected
but on my next component when I print again the same data it shows undefinied:
import { Component, OnInit } from '#angular/core';
import {dataBaseService} from "../dataBase.service";
#Component({
selector: 'app-modelo',
templateUrl: './modelo.component.html',
styleUrls: ['./modelo.component.scss'],
providers: [dataBaseService]
})
export class ModeloComponent implements OnInit {
ngOnInit() {
console.log(this.dataService.serviceData);
}
constructor(public dataService: dataBaseService) {
}
}
console.log(this.dataService.serviceData); it returns "undefined"..
So how can I save that data that I putted on the first component and beeing able to show it on another component? what am I missing?
UPDATE:
Some people like me didn't find an answer to the other question like this one on stack and that's because Instead of adding the providers individually you have to add them globably (on module.ts) !!!!!!!!!!!!

As you said you have already added the provider on the module level,try commenting out the providers declaration from components.

Related

Angular - trying to use child component function in parent view but I'm gettting an error

When I use #ViewChild I get the error that the component is not defined.
When I use #ViewChildren I get the error that the function from that component is not a function.
I am new to using child components in Angular so I'm not sure why it's doing this when I do have the child component defined in the parent component and when it's clearly a function in the child component.
I don't want to have to define every function from the child in the parent or else what's even the point of using a separate component.
Child Component
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-mood',
templateUrl: './mood.component.html',
styleUrls: ['./mood.component.css']
})
export class MoodComponent implements OnInit {
moodColors = ['red', 'orange', 'grey', 'yellow', 'green'];
constructor() { }
ngOnInit(): void {
}
chooseMood() {
alert(this.moodColors);
}
}
Parent Component (Relavant Part of Version with "ERROR TypeError: ctx_r3.mood is undefined")
import { Component, OnInit, ViewChild, ViewChildren } from '#angular/core';
import { ViewEncapsulation } from '#angular/core';
import { MoodComponent } from '../mood/mood.component';
#Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CalendarComponent implements OnInit {
#ViewChild('mood') mood: MoodComponent = new MoodComponent;
Parent Component (Relavant Part of Version with "ERROR TypeError: ctx_r3.mood.chooseMood is not a function")
import { Component, OnInit, ViewChild, ViewChildren } from '#angular/core';
import { ViewEncapsulation } from '#angular/core';
import { MoodComponent } from '../mood/mood.component';
#Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CalendarComponent implements OnInit {
#ViewChildren('mood') mood: MoodComponent = new MoodComponent;
Parent View
<h2 (click)="mood.chooseMood()"></h2>
You don't explicitly initialize view children via new.
Just use:
#ViewChild('mood') mood : MoodComponent;
If that doesn't work post a Stackblitz example which I can edit to resolve the issue.
Also, using ViewChild is more of an exception in Angular, and your use of it points to a probable design issue. More likely you child component should emit via an Output to the parent.
Regarding outputs, you can do something like this - though it is hard to give a precise answer without deeper knowledge of what you are trying to achieve:
export class MoodComponent implements OnInit {
#Input() moodId: string;
#Output() chooseMood = new EventEmitter<string>();
moodClicked(){
this.chooseMood.emit(moodId);
}
}
export class CalendarComponent implements OnInit {
moodChosen(string: moodId){
console.log(moodId);
}
}
// Calendar template:
<app-mood
moodId="happy"
(chooseMood)="moodChosen($event)"
></app-mood>
1 - you have to use this code
#ViewChild('mood') mood : MoodComponent;
when you are using #ViewChildren it will return list of items with the 'mood' name then you have to use this code
mood.first.chooseMood() ;
its better use ViewChildren when there is ngIf in your element
2- no need new keyword for initialize mood variable
it would be fill after ngOnInit life cycle fires

Problem calling one Angular component from another component

At work, I have run into a problem using Angular. I have this kind of Angular component:
#Component({
selector: 'foo',
templateUrl: 'foo.html'
})
export class FooComponent {
#Input() data: string;
content: string;
ngOnInit() {
this.content = this.data;
}
setValue(data) {
this.content = data;
}
}
This is initialized from my main Angular component in a code block such as this:
this.components = [FooComponent, BarComponent, BazComponent, QuuxComponent];
Now this works so far. But if I try to call the setValue() function with this.components[0].setValue("Hello world!"); I get an error "this.components[0].setValue is not a function."
What is the reason for this and how can I fix it?
This seems like a very very weird way to work with components in angular.
You really don't want to break encapsulation by calling methods inside one component from another component.
I personally haven't seen this kind of component referencing anywhere (and have doubts it is a correct approach).
There is no reason to duplicate the data property in the content.
You can pass values in the template. Or use a service if you don't have direct access to the template.
Here is a very basic example on how to modify data from the parent using a template and #Input.
app.component.ts
import { Component } from "#angular/core";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
message = "I am a message from the parent";
}
app.component.html
<app-child [content]='message'></app-child>
child.component.ts
import { Component, OnInit, Input } from "#angular/core";
#Component({
selector: "app-child",
templateUrl: "./child.component.html",
styleUrls: ["./child.component.css"]
})
export class ChildComponent implements OnInit {
#Input("content") public content: string;
constructor() {}
ngOnInit() {}
}
child.component.html
<p>{{content}}</p>

Angular 7 Service providedIn: 'root'

I'm very new to angular development so please forgive me if this is a very basic question
But I have a cart service which I have at the moment simply has a simple console log function
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class CartService {
constructor( ) {}
public addItem() {
console.log('Hello');
}
}
and basically I cannot figure out how to use this service within a NG Module that I have installed, I have successfully used it in other components via the constructor but the ngmodule doesn't have this?
I get the fact that it's a singleton at the app-module level by using the providedIn: 'root' tag added in angular 6
but just can't figure out how to call cartService.addItem()?
Thanks if anyone can help!
You can use Dependency Injection like this to call the service
export class AppComponent {
constructor(private cartService: CartService) {
}
doSomething() {
this.cartService.addItem();
}
}
Below is the sample code of how to use service in component:
Component.ts
import { Component, OnInit} from '#angular/core';
import { yourSeerviceName } from "PATH_TO_SERVICE";
#Component({
selector: 'app-dummy',
styleUrls: ['dummy.component.sass'],
templateUrl: 'dummy.component.html'
})
export class yourComponent implements OnInit {
// you can provide any name for variable it's upto you
constructor(private dummyService:yourSeerviceName) {
}
//access the method in you'r service by performing below action.
this.dummyService.yourMethod();
}
If you created a new module, you need to introduce the service to your module, by going to the .module.ts file and adding your service to the providers array. It will be something like:
providers: [
CartService
],

[angular 4 / typescript ]import component path not reconized. But seems valid and should work

I am building a router component in angular and typescript.
observe my current project structure below.
Lets focus on the landingPageComponent
observe by the image that my path to the component is valid but is not recognized.
my code in my landingpageComponent.ts file:
import { Component, OnInit, ViewChild } from '#angular/core';
import {NgForm} from '#angular/forms';
#Component({
selector: 'app-landing-page',
templateUrl: './landingpage.component.html',
styleUrls: ['./landingpage.component.css']
})
export class LandingPageComponent implements OnInit {
#ViewChild('f')citySubmit : NgForm;
cities:string[]=['Chicago', 'New Mexico', 'London'];
ngOnInit() {
}
}
the proper imports are done in the app.module.ts file without error. Meaning the path is recognized.
I am hoping I am just making a silly mistake somewhere
Thank you.
In your app.routing.module.ts it should be,
import { LandingPageComponent } from './landingpage/landingpage.component';
import { HowItWorksComponent } from './howitworks/howitworks.component'

Fetching a json file in Angular 2 [duplicate]

This question already has answers here:
How to get a json file in Angular 2 using the Http class?
(3 answers)
Closed 6 years ago.
There are few solutions on SO, but apparently they are deprecated. Angular 2 changes all the time...
Im trying to fetch a json file to my file.
There's a items.json file.
I'm wondering if I am able to make this work in just one file? I mean, just inside the app.component.ts? app.component.ts file actually looks like:
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { Injectable } from '#angular/core';
#Component({
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
#Injectable()
export class AppServices{
constructor(private http: Http) {
let obj;
this.getJSON().subscribe(data => obj=data, error => console.log(error));
}
public getJSON(): {
return this.http.get("./items.json")
.map((res:any) => res.json())
}
}
export class AppComponent {
let items = getJSON();
}
}
Or maybe I have to include a app.service.ts file? And drop there the code fetching the json? It was so easy to do it in Angular1, why they made this so complicated...
I'm looking for the shortest solution as it is possible I will upvote every answer. Thank u in advance
EDIT
I got another code:
import { Component } from '#angular/core';
import { Http } from '#angular/http';
#Component({
selector: 'watchlist',
templateUrl: './watchlist.component.html',
styleUrls: ['./watchlist.component.css']
})
export class WatchlistComponent {
data;
constructor(private http:Http) {
this.http.get('items.json')
.subscribe(res => this.data = res.json());
}
}
How to load this data into my items variable?
// A function You can declare an app
app() {
return this.http.get('/config.json');
}
this.app().subscribe((data: any) => {
}

Categories

Resources