Share service API data between initial components in Angular 6 - javascript

I'm trying to have a navbar with categories and a home component that also uses those categories. I don't want to have to call my API twice and I will use that same categories variable in other places. I tried doing the following:
Data Service
This service gets the data from the api url and returns the subscribable object.
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
api_url: string = "https://apiurlhere";
categories: Object;
constructor(private http: HttpClient) { }
getCategories(){
return this.http.get(this.api_url+'/categorylisting/?z=1');
}
getZones(){
return this.http.get(this.api_url+'/zones/');
}
}
Navbar Component
The Navbar component makes use of the categories variable to show the different options, this works fine since the subscribe is in this component.
import { Component, OnInit } from '#angular/core';
import { trigger, state, transition, animate, style } from '#angular/animations';
import { DataService } from '../data.service';
#Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss'],
animations: [
trigger('slideInOut', [
state('in', style({
overflow: 'hidden',
height: '*'
})),
state('out', style({
overflow: 'hidden',
height: '0px'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
])
]
})
export class NavbarComponent implements OnInit {
categories: Object;
constructor(private data:DataService) { }
ngOnInit() {
this.data.getCategories().subscribe( data => {
this.categories = data
for(let category in this.categories){
this.categories[category].productsOpen='out';
for(let product in this.categories[category].product){
this.categories[category].products[product].active = false;
}
}
this.data.categories = this.categories;
});
}
openProducts(index){
this.categories[index].productsOpen = this.categories[index].productsOpen === 'out' ? 'in' : 'out';
}
setActiveProduct(index, productIndex){
for(let category in this.categories){
for(let product in this.categories[category].products){
this.categories[category].products[product].active = false;
}
}
this.categories[index].products[productIndex].active = true;
}
}
Home Component
My Home component also makes use of the categories variable, so I want to know how I can get it here since it is always undefined even if it changes in the service.
import { Component, OnInit } from '#angular/core';
import { DataService } from '../data.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
categories: Object;
constructor(private data:DataService) { }
ngOnInit() {
this.categories = this.data.categories;
}
}
Am I doing this right? I'm used to react and redux and in there the render method would run every time a setState was called to change the state, when does angular know when the component's variables have changed? I just want to save a global variable with my data so I can reuse it without calling the API every time. Thank You.

You can cache the observable in your service like:
export class DataService {
someProperty;
api_url: string = "https://apiurlhere";
categories: Object;
constructor(private http: HttpClient) { }
getCategories(){
if(!this.someProperty) {
this.someProperty = this.http.get(this.api_url+'/categorylisting/?z=1');
}
return this.someProperty;
}
}
You can also go for angular Http interceptors else you can also opt for rxjs operator shareReplay

You could try calling your API in the constructor of the DataService
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
api_url: string = "https://apiurlhere";
categories: Object;
constructor(private http: HttpClient) {
this.getCategories().subscribe(data => this.categories = data);
}
getCategories(){
return this.http.get(this.api_url+'/categorylisting/?z=1');
}
getZones(){
return this.http.get(this.api_url+'/zones/');
}
}
and then just get the categories in the NavBar component just as you did in the Home component.
ngOnInit() {
this.categories = this.data.categories;
}

Related

check boolean value again and again

I am trying to build infinite scroll for my cards.
I am using a variable reload in data.service to check for need to load more data which is getting set to true when page end is getting reached.
The variable setting to true is done by app.component
The content population is done in post.component
And ```reload`` is present in data.service which is using http service to fetch for content from php server.
Curently I am using observable and trying to access reload status repeatedly but it is getting subscribed only once on Init.
app.component.ts
import { Component,HostListener } from '#angular/core';
import * as M from 'materialize-css';
import {DataService} from './current/posts/post-card/data.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
title = 'cosmos';
constructor(private scrollSet: DataService){}
#HostListener('scroll', ['$event'])
onScroll(event:any)
{
if (event.target.offsetHeight + event.target.scrollTop >= event.target.scrollHeight-100)
{
console.log("noww");
this.scrollSet.setValue(true);
}
}
}
post.component.ts
import { Component, OnInit} from '#angular/core';
import {DataService} from './data.service';
import { DomSanitizer } from '#angular/platform-browser';
import {Title} from "#angular/platform-browser";
#Component({
selector: 'app-post-card',
templateUrl: './post-card.component.html',
styleUrls: ['./post-card.component.css']
})
export class PostCardComponent implements OnInit {
constructor(private data: DataService,public sanitizer: DomSanitizer,private titleService:Title)
{
this.titleService.setTitle("Current Feed | Cosmos");
}
received = 'none';
posts: any = [];
ngOnInit()
{
this.data.getPostData().subscribe(data =>
{
this.posts.push(data);
this.received='success';
},
error =>
{
this.received='error';
});
this.data.getValue().subscribe((value) => {
this.data.getPostData().subscribe(data =>
{
this.posts.push(data);
this.received='success';
},
error =>
{
this.received='error';
});
});
}
}
data.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class DataService {
private reload: BehaviorSubject<boolean>;
constructor(private http: HttpClient)
{
this.reload = new BehaviorSubject<boolean>(false);
}
fetchGap=5; // use this to set number of results wanted per fetch
fetchEnd:number= 0;
setValue(newValue): void {
this.reload.next(newValue);
}
getValue(): Observable<boolean> {
return this.reload.asObservable();
}
getPostData(){
this.fetchEnd+=this.fetchGap;
return this.http.get('http://localhost:1234/Server/getPosts.php?fetchEnd='+this.fetchEnd+'&fetchGap='+this.fetchGap);
}
}
the problem is that you haven't set the value of reload to false after your treatment.
try to check inside post.component.ts. here is a portion of that code, the block which suscribe to reload.
post.component.ts reload block
this.data.getValue().subscribe((value) => {
if(value){
this.data.getPostData().subscribe(data =>
{
this.posts.push(data);
this.received='success';
},
error =>
{
this.received='error';
});
this.data.setValue(false);
}
});

Property '' does not exist on type 'Object'

I was working all day in angular. Everything worked fine all day.
Restarted the server (ng serve). And now suddenly there are alot of errors.
I managed to fix most but I am stuck with this one.
This is the main part of the component .ts file:
import { Component, OnInit } from '#angular/core';
import { HttpService } from '../http.service';
#Component({
selector: 'app-playboard',
templateUrl: './playboard.component.html',
styleUrls: ['./playboard.component.scss']
})
export class PlayboardComponent implements OnInit {
brews: Object;
constructor(private _http: HttpService) { }
ngOnInit() {
this._http.myMethod().subscribe(data => {
this.brews = data;
this.dices = this.brews.myBox;
this.diceSeed = this.brews.boxID;
console.log(this.brews);
});
}
And this is the http.service.ts file:
import { Injectable } from '#angular/core';
import {HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private http: HttpClient) { }
myMethod() {
return this.http.get<Object>('https://localhost:44398/api/boggle');
}
myWordMethod(word) {
var url = 'https://localhost:44398/api/wordpoints/' + word;
return this.http.get<Object>(url);
}
}
It was working all day and suddenly these strange errors appear.
Does anyone have a clue of what could be wrong? Thanks alot!
Remove Object from your http calls. Using the generic is optional, especially if you haven't typed out your response.
import { Injectable } from '#angular/core';
import {HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private http: HttpClient) { }
myMethod() {
return this.http.get('https://localhost:44398/api/boggle');
}
myWordMethod(word) {
var url = 'https://localhost:44398/api/wordpoints/' + word;
return this.http.get(url);
}
}
On brews, declare it as any:
import { Component, OnInit } from '#angular/core';
import { HttpService } from '../http.service';
#Component({
selector: 'app-playboard',
templateUrl: './playboard.component.html',
styleUrls: ['./playboard.component.scss']
})
export class PlayboardComponent implements OnInit {
brews: any;
constructor(private _http: HttpService) { }
ngOnInit() {
this._http.myMethod().subscribe(data => {
this.brews = data;
this.dices = this.brews.myBox;
this.diceSeed = this.brews.boxID;
console.log(this.brews);
});
}
You can ignore these by simply delcaring them as the any type. For instance;
myWordMethod(word: any) {
..
}
this._http.myMethod().subscribe(data: any => {
..
});
That said declaring the actual type for TypeScript is often preferred. For Instance if your API sends back a common object with particular properties then declare it as such;
interface MyMethodResponse {
someProperty: string;
someNumber: number;
someArray: string[];
}
this._http.myMethod().subscribe((myMethodResponse: MyMethodResponse) => {
// TypeScript now knows that these properties exists on the response object
console.log(myMethodResponse.someArray);
console.log(myMethodResponse.someNumber);
console.log(myMethodResponse.someProperty);
});

ANGULAR. Send array data get it of Itunes API; from component-search to component-main, via service

In angular 7. I need to send an Array information get it from Itunes Api, which is included in a component called "search", to another component called "catalog". I've understand that in this case I've to use a service which allows to share the info between them. Here's some code. What's wrong?
I've tried with viewchild, input, output, but there's no result; because both components aren't "relatives".
"search"
"search"
import { Component, OnInit, Output, EventEmitter } from '#angular/core';
import { RequestService } from '../../services/request/request.service';
import {DataShareService} from '../../services/dataShare/data-share.service';
import { Music } from '../../models/music';
#Component({
selector: 'search',
styleUrls: ['./ion-searchbar.component.sass'],
templateUrl: './ion-searchbar.component.html',
providers: [RequestService, DataShareService],
})
export class IonSearchBarComponent implements OnInit {
public searchResults: Music[];
public searchValue: string;
constructor(public _requestService: RequestService, private _dataShareService: DataShareService) {}
ngOnInit() {
this._dataShareService.$sendDataObservable.subscribe(
data => {
this.searchResults = data
})
}
sendData(searchResults: Music[]){
console.log("executat");
this._dataShareService.sendData(searchResults);
}
search(){
this._requestService.getMusic(this.searchValue).subscribe(
result => {
this.searchResults = result.results;
console.log(result.results);
this.sendData(this.searchResults);
},
error =>{
console.log(<any>error);
}
);
}
}
"service"
import { Injectable } from '#angular/core';
import { Music } from '../../models/music';
import { Subject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class DataShareService {
private _sendDataSubject = new Subject<Music[]>();
$sendDataObservable = this._sendDataSubject.asObservable();
constructor() { }
sendData(data: Music[]){
this._sendDataSubject.next(data);
console.log(data);
}
}
"catalog"
import { Component, OnInit, Input } from '#angular/core';
import {RequestService} from '../../services/request/request.service';
import {DataShareService} from '../../services/dataShare/data-share.service';
import { Music } from '../../models/music';
#Component({
selector: 'catalog',
templateUrl: './catalog.component.html',
styleUrls: ['./catalog.component.sass'],
providers: [RequestService, DataShareService]
})
export class CatalogComponent implements OnInit {
public title: any;
public InfoLlegada: any;
constructor(private _dataShareService: DataShareService) {}
ngOnInit() {
console.log(this.InfoLlegada)
this._dataShareService.$sendDataObservable.subscribe(
data => {
this.InfoLlegada = data
console.log(data);
});
}
}
Not sure if this is the actual cause, but there an issue with your this binding in getMusic subscription in search component. Try this.sendData.call(this, result.results);

Storing and accessing a global flag/variable in each component, The value keeps changing

I am trying to make a global service class which will store few variables which will influence behaviour on HTML components base on flags.
My current only flag is a BehaviourSubject which navbar component subscribes to update a navbar with different buttons. The issue is when I refresh the page in a browser the flag reverse to the original value and forgets what has set before. The current scenario is when user log in the flag is being set to true and should stay true until a user logs out. It may not be a right way to do it so if there is a better way of approaching it; then I am happy to implement it.
Data sharing class:
import {
Injectable
} from '#angular/core';
import {
BehaviorSubject
} from 'rxjs';
#Injectable()
export class ServiceClassDatasharing {
public isUserLoggedIn: BehaviorSubject < boolean > = new BehaviorSubject < boolean > (false);
public setUserLoggedInStatus(status) {
this.isUserLoggedIn.next(status);
}
}
Nav Component:
import {
Component,
OnInit
} from '#angular/core';
import {
MatDialog,
MatDialogRef,
MAT_DIALOG_DATA
} from '#angular/material';
import {
Inject
} from '#angular/core';
import {
ServiceClassDatasharing
} from '../service/service-class-datasharing';
import {
ServiceClassAuth
} from '../service/service-class-auth';
import {
SigninComponent
} from './../signin/signin.component';
import {
Router
} from '#angular/router';
#Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
id_token: Boolean;
username: String;
constructor(public dialog: MatDialog, private dataSharingService: ServiceClassDatasharing,
private authService: ServiceClassAuth, private router: Router) {
this.dataSharingService.isUserLoggedIn.subscribe(res => {
this.id_token = res;
if (this.id_token) {
const user = JSON.parse(localStorage.getItem('user'));
this.username = user['user'].user_username;
}
});
if (!this.id_token) {
router.navigate(['index']);
}
}
ngOnInit() {}
openDialog(): void {
let dialogRef = this.dialog.open(SigninComponent, {
width: '450px',
data: {}
});
}
public logout() {
this.authService.logout().subscribe(res => {
if (res['success']) {
localStorage.clear();
this.dataSharingService.setUserLoggedInStatus(false);
}
});
this.router.navigate(['index']);
}
}
Index Component as an example it should redirect a user to dashboard if the global flag is set to true.
import {
Component,
OnInit
} from '#angular/core';
import {
ServiceClassDatasharing
} from '../service/service-class-datasharing';
import {
Router
} from '#angular/router';
#Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
constructor(private dataSharingService: ServiceClassDatasharing, private router: Router) {
if (this.dataSharingService.isUserLoggedIn.value) {
this.router.navigate(['dashboard']);
}
}
ngOnInit() {}
}
Try using localStorage variable to achieve the same .
Create a function in service class which will set the variable with token if user logs in and function to get the same token.
const key = 'abcde'
setUseLoggedIn(token){
localStorage.setItem(this.key,token);
}
getUserLoggedIn(){
return localStorage.getItem(this.key);
}
set token as null if user is not logged in and check for the same when retrieving the token.

(Angular2) JSON data (http.get()) is undefined, and data is not updated in the component

My http-data.service accepts json for output in the component template. Initially, the console shows that the first few calls are given undefined, and the following calls are already taking json, but also if you check the component, then the component shows that the method that outputs the data to the component is called only once and since the data has not yet arrived it writes undefined , But not updated after the arrival of json. Help please understand why? Thank you
My http-data.service:
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
import {Response} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class HttpService{
constructor(private http: Http) {}
getDataOrganizations(): Observable<any[]>{
return this.http.get('http://localhost:3010/data')
.map((resp:Response)=>{
let dataOrganizations = resp.json().organization;
return dataOrganizations;
});
}
getDataModules(): Observable<any[]> {
return this.http.get('http://localhost:3010/data')
.map((resp: Response)=> {
let dataModules = resp.json().modules;
return dataModules;
});
}
getDataPresets(): Observable<any[]> {
return this.http.get('http://localhost:3010/data')
.map((resp: Response)=> {
let dataPresets = resp.json().presets;
return dataPresets;
});
}
getDataModuleItems(): Observable<any[]> {
return this.http.get('http://localhost:3010/data')
.map((resp: Response)=> {
let dataModuleItems = resp.json().module_items;
return dataModuleItems;
});
}
}
My data-all.service
import { Injectable, EventEmitter } from '#angular/core';
import {Response} from '#angular/http';
import { ModuleModel } from './model-module';
import { ModuleItemsModel } from './model-module-items';
import data from '../data/data-all';
import { PriceService } from './price.service';
import { HttpService } from './http-data.service';
#Injectable()
export class ModuleDataService {
constructor(private priceService: PriceService, private httpService: HttpService){
this.dataMinMaxSum = {minSum: 0, maxSum: 0}
}
private currentPopupView: EventEmitter<any> = new EventEmitter<any>();
private dataModules: ModuleModel[] = this.getDataModules();
private dataMinMaxSum: {};
private dataCalculateVariationOrg: any[];
private dataChangeExecutor: any[];
subscribe(generatorOrNext?: any, error?: any, complete?: any) {
this.currentPopupView.subscribe(generatorOrNext, error, complete);
}
calculte(){
return this.priceService.getDataPrice();
}
getDataModules(){
this.httpService.getDataModules().subscribe(((modules)=>{this.dataModules = modules; console.log(this.dataModules);}));
console.log('dataModules');
console.log(this.dataModules);
return this.dataModules;
}
---------------------------------------------------------------------------
}
My left-block.component
import { Component, OnInit} from '#angular/core';
import { ModuleDataService } from '../../service/data-all.service';
import { ModuleModel } from '../../service/model-module';
#Component({
moduleId: module.id,
selector: 'modules-left-block',
templateUrl: './modules-left-block.html',
styleUrls: ['modules-left-block.css']
})
export class ModuleLeft implements OnInit{
modules: ModuleModel[];
constructor(private modulesAll: ModuleDataService){}
ngOnInit(){
this.modules = this.modulesAll.getDataModules();
console.log("view");
console.log(this.modulesAll.getDataModules());
}
onToggle(module: any){
this.modulesAll.toggleModules(module);
}
}
My left-block.component.html
<div class="modules-all">
<div class="modules-all-title">Все модули</div>
<div class="module-item" *ngFor="let module of modules" [ngClass]="{ 'active': module.completed }" (click)="onToggle(module)">{{module?.title}}</div>
</div>
In the component this.modulesAll.getDataModules () method is why it is executed only once without updating (write in console => undefined), if there are any thoughts, write, thanks.
This behaviour is due to the .subscribe() method does not wait for the data to arrive and I'm guessing you already know this. The problem you're facing is because, you have .subscribe to the getDataModules() service in the wron place. You shouldn't subscribe to a service in another service (at leat in this case). Move the subscribe method to the left-block.component and it should work.
getDataModules() {
this.httpService.getDataModules().subscribe(((modules) => {
this.dataModules = modules;
console.log(this.dataModules);
}));
console.log('dataModules');
console.log(this.dataModules);
return this.dataModules;
}
It should look somethig like this:
#Component({
moduleId: module.id,
selector: 'modules-left-block',
templateUrl: './modules-left-block.html',
styleUrls: ['modules-left-block.css']
})
export class ModuleLeft implements OnInit {
modules: ModuleModel[] = new ModuleModel();
constructor(private modulesAll: ModuleDataService, private httpService: HttpService) {}
ngOnInit() {
this.getDataModles();
//this.modules = this.modulesAll.getDataModules();
console.log("view");
//console.log(this.modulesAll.getDataModules());
}
onToggle(module: any) {
this.modulesAll.toggleModules(module);
}
getDataModules(): void {
this.httpService.getDataModules().subscribe(((modules) => {
this.modules = modules;
console.log(this.dataModules);
}));
}
}

Categories

Resources