Angular component communication - using ngIf with booleans from a service - javascript

I have 2 sibling components and I am showing an API result if there is a successful response and an API Failure error message if there is an API error. If there is an API Failure in both components, I need to show only 1 API Failure error message. I have managed to do this and I used a service to define booleans and use them in the components. However, I am wondering if there is a better solution like using Input, Output, EventEmitter or Subject.
message.component.html
<div *ngIf="isTodosLoaded && !appService.isAPIError">{{ todos.title }}</div>
<div *ngIf="!isTodosLoaded && appService.isAPIError">{{ appService.APIErrorMessage }}</div>
message2.component.html
<div *ngIf="isTodos2Loaded && !appService.isAPI2Error">{{ todos2.title }}</div>
<div *ngIf="!isTodos2Loaded && appService.isAPI2Error && !appService.isAPIError">{{ appService.APIErrorMessage }}</div>
message.component.ts
export class MessageComponent implements OnInit {
isTodosLoaded = false;
todos;
constructor(private messageService: MessageService,
private appService: AppService) { }
ngOnInit() {
this.messageService.getData()
.subscribe(
(response) => {
this.todos = response;
this.isTodosLoaded = true;
},
(error) => {
this.appService.isAPIError = true;
}
)
}
}
message.component.ts
export class Message2Component implements OnInit {
isTodos2Loaded = false;
todos2;
constructor(private message2Service: Message2Service,
private appService: AppService) { }
ngOnInit() {
this.message2Service.getData()
.subscribe(
(response) => {
this.todos2 = response;
this.isTodos2Loaded = true;
},
(error) => {
this.appService.isAPI2Error = true;
}
)
}
}
app.service.ts
export class AppService {
public isAPIError = false;
public isAPI2Error = false;
public APIErrorMessage = "API Failure"
constructor() { }
}
Source code: https://stackblitz.com/edit/angular-pwwicc

There is multiple ways to achieve that:
fetch the data in the parent and send it to the child with Input.
fetch the data somewhere in the app and save it in a service (in a Subject or in a variable) and get the data in your child from the service.
use ngrx for shared state between component.
second example:
in the parent:
fetch(...).subscribe(result => this.myService.setResult(result))
in your service:
result = new BehaviorSubject(null)
setResult(result):void{
this.result.next(result);
}
And in your child component:
this.myService.result.subscribe(result => {...})

Related

Cannot read properties of undefined on synchronous call to a rest api

I'm new to angular and I wasn't sure how to implement synchronous api calls. I implemented async/await from a few articles I read but it still seems like the variables are undefined meaning the console is printing before even initializing the variable. I need it to be synchronous because code further down the cycle function depends on accurate variables.
I'm making a small program where people can upload their own images and it will be displayed on the stage component. I'm saving the images as a blob on a mysql database and retrieving them one at a time depending on the names provided in my nameList array variable
What am I doing wrong when calling the api via synchronous call?
stage.component.html
<div class="container">
<div class="slideshow" *ngIf="retrievedImage">
<ng-container>
<img [src]="retrievedImage"/>
<h1 *ngIf="!database_populated" style="color: red;">No Photo's to show. Please go back and upload</h1>
</ng-container>
</div>
</div>
stage.component.ts
import { HttpClient } from '#angular/common/http';
import { Component, OnInit } from '#angular/core';
import { interval } from 'rxjs';
import { ImagingService } from '../../services/imaging.service';
#Component({
selector: 'app-stage',
templateUrl: './stage.component.html',
styleUrls: ['./stage.component.css']
})
export class StageComponent implements OnInit {
constructor(private httpClient: HttpClient, private imageService: ImagingService) { }
retrieveResponse: any;
public namesList: any;
imageName: string = "eating.jpg";
base64Data: any;
retrievedImage: any = null;
currentImage = 0;
public database_populated: boolean = false;
totalImages: any;
ngOnInit(): void {
this.checkCount().then(count => {
if (count > 0 ) {
this.database_populated = true
console.log("database is populated. going to cycle")
this.cycle()
}
else {
this.database_populated = false;
}
}) }
cycle(){
console.log("entering cycle")
interval(10000).subscribe(x =>
{
// update how many images there are in the database
this.checkCount().then(data => {
this.totalImages = data
})
console.log(this.totalImages)
//update the list of image names found in the database
this.updateNamesList().then(nameList => {
this.namesList = nameList;
})
console.log(this.namesList)
if (this.currentImage == this.totalImages){
console.log("inside mod")
this.currentImage = this.currentImage % this.totalImages
}
else
{
console.log("printing pictures")
// display the Nth image in the list
this.imageName = this.namesList[this.currentImage]
// increment the image count in case there is another image added to the database
this.currentImage = this.currentImage + 1
this.getImage()
}
});
}
getImage() {
//Make a call to Sprinf Boot to get the Image Bytes.
this.httpClient.get('http://localhost:8080/halloween/get/' + this.imageName)
.subscribe(
res => {
this.retrieveResponse = res;
this.base64Data = this.retrieveResponse.picByte;
this.retrievedImage = 'data:image/jpeg;base64,' + this.base64Data;
}
);
}
async updateNamesList(){
return await this.imageService.updateNamesList()
}
async checkCount(){
return await this.imageService.checkCount()
}
}
imaging.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ImagingService {
constructor(private httpClient: HttpClient) { }
public updateNamesList() {
return this.httpClient.get('http://localhost:8080/halloween/allnames').toPromise();
}
public checkCount() {
return this.httpClient.get('http://localhost:8080/halloween/check').toPromise();
}
}
this is a snippet of the browser console errors and it shows the variables as undefined even though I place the promise prior to the console.log
Your code will not work with asynch. Here is the order of execution.
// command 1
this.checkCount().then(data => {
//command 3
this.totalImages = data
});
// command 2, totalImages will be undefined.
console.log(this.totalImages)
There is no guarantee about time at command 2, because we fetch data through network, so delay time may take few seconds.
You can await the result of checkCount to make sure we have data through rest api.:
this.totalImages = await this.checkCount();
Or you can do other things after rest api have an data.
this.checkCount().then(data => {
this.totalImages = data
doSomethingWithTotalImagesHere();
});

Global Variables undefined in ng-template

I am using a globals file to set key data needed for the application. Everything works until you use the browser refresh button. Once that is clicked, all the data I am loading from the globals.ts file comes back as undefined when the template is loaded. After the template is loaded, the promise populates the data. I need the promise data to populate before the ng-template binding.
Notice that I am trying to populate the global data by calling this.globals.init(token) from the app.component. Then in the helpful-links template I am trying to build a url based on data passed in from the parent component (myAccount.component). Oddly enough, data in the parent component also uses the globals file, and populates fine. Where did I go wrong?
-app.component
constructor(public globals: Globals){}
async ngOnInit() {
...
this.globals.init(token);
...
}
-Globals.ts
#Injectable()
export class Globals {
async init(token:string): Promise<any>{
if(token === undefined || token === '') {
token = this.oidcSecurityService.getIdToken();
}
const decoded = jwt_decode(token);
console.log(decoded, '<<<<<<<<<--------- decoded!', this.title)
this.email = decoded.email;
await this.get('getuserdata', {}).toPromise()
.then(async (res) => {
// THIS IS THE NEEDED DATA THAT COMES BACK AFTER THE BINDING. all except localstorage is undefined
localStorage.setItem('email', res['body'][0].email);
this.userRole = res['body'][0].title;
this.setUserId(res['body'][0].userid);
this.userid = res['body'][0].userid;
this.email = res['body'][0].email;
this.subscriberid = res['body'][0].fk_tk_subscriber_id;
this.isManagerRole = res['body'][0].title === 'HR Admin' ? true : false;
this.setTitle(res['body'][0].title);
this.profilePic = res['body'][0].profilephotourl;
});
}
-my7Account.component.html file
...
<app-tk-helpful-links [glob]='this.globals'></app-tk-helpful-links>
...
--helpful-links template
#Component({
selector: 'app-tk-helpful-links',
templateUrl: './tk-helpful-links.component.html',
styleUrls: ['./tk-helpful-links.component.scss']
})
export class HelpfulLinksComponent implements OnInit {
#Input() glob: Globals;
public res: {};
subscription: Subscription;
async getHelpfulLinks(): Promise<any> {
if(this.globals.userid === undefined) {
this.globals.init('');
}
return this.dataSvc.get(`gethelpfulLinks/${this.glob.userid}/${this.glob.subscriberid}`, {})
.subscribe(res => {
this.res = res['body'];
});
}
constructor(
private dataSvc: TkDataService,
public globals: Globals
) {
}
async ngOnInit() {
this.getHelpfulLinks();
}
}

Angular Component: Impossible to loop through an array of object with TypeScypt

can any one please tell me why I can not loop through this array?
In ngOnInit, everything works fine. I got an array that I successfully display in the template.
But in ngAfterViewInit, console.log show the array but when looping through with "for of" or "forEach", nothing works.
import { JobsService } from '../jobs.service';
import {Job} from '../models/Job';
#Component({
selector: 'app-job',
templateUrl: 'job.component.html'
})
export class JobComponent implements OnInit, AfterViewInit {
title = 'Job';
jobs: Job[] = [];
InProcess = '';
CurrentPartner = '';
ShowProcess = false;
sended = '';
constructor(private jobsService: JobsService) {
}
ngOnInit() {
this.jobs = this.jobsService.getJobs();
}
ngAfterViewInit() {
console.log(this.jobs); // Show the array
// Nothing happened when looping through the array
this.jobs.forEach((oneJob) => {
console.log(oneJob);
});
}
}
Screenshot of the console in Google Chrome
The content of the service:
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {Job} from './models/Job';
interface IJob {
message: string;
jobs: any[];
}
#Injectable({
providedIn: 'root'
})
export class JobsService {
constructor(private httpClient: HttpClient) { }
private REST_API_SERVER = 'http://localhost:8080/myband/api/getjobs.php';
private REST_API_SERVER_SEND = 'http://localhost:8080/myband/api/sendjob.php';
jobList: Job[] = [];
errorMessage: any;
message: string;
static handleError(err: HttpErrorResponse) {
let errorMessage = '';
if (err.error instanceof ErrorEvent) {
errorMessage = `An error occurred: ${err.error.message}`;
} else {
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return throwError(errorMessage);
}
public getJobs() {
this.requestJobs().subscribe(
iJob => {
this.message = iJob.message;
for (const job of iJob.jobs) {
const oneJob: Job = new Job(job);
this.jobList.push(oneJob);
}
},
error => this.errorMessage = error as any
);
return this.jobList;
}
public requestJobs(): Observable<IJob> {
return this.httpClient.get<IJob>(this.REST_API_SERVER).pipe(
catchError(JobsService.handleError)
);
}
}
The first thing I want to say to you is about isolation of responsibilities.
Your service must have just one job: provider one way to access your data; It means your logic inside getJobs() method could be done in your component.
export class JobsService {
constructor(
private httpClient: HttpClient,
) {}
private REST_API_SERVER = 'http://localhost:8080/myband/api/getjobs.php';
public requestJobs(): Observable<IJob> {
return this.httpClient.get<IJob>(this.REST_API_SERVER);
}
}
Now, you can handler your data in your component.
import { JobsService } from '../jobs.service';
#Component({
selector: 'app-job',
templateUrl: 'job.component.html'
})
export class JobComponent implements OnInit, AfterViewInit {
title = 'Job';
jobs$;
InProcess = '';
CurrentPartner = '';
ShowProcess = false;
sended = '';
constructor(private jobsService: JobsService) {
}
ngOnInit() {
this.jobs$ = this.jobsService.requestJobs();
}
ngAfterViewInit() {
this.jobs$
.pipe(
map(() => {}), // change your data here
catchError(() => {}) // handler your error here;
)
.subscribe(
() => {} // have access to your final data here.
);
}
}
Things to know:
You can remove the subscribe() execution and use the async pipe in your template;
The use of the operator map in pipe() is optional, you can handler your final data directly from your first callback subscribe().
You can convert your Observable to Promise using toPromise() method in one observable. Don't forgot async / await in your ngAfterViewInit.
Let me know if there is something I can help.
Try:
Object.keys(this.jobs).forEach(job => {
console.log(this.jobs[job]);
});
Try to assign an iterator function with below part replacement by this code:
// Nothing happened when looping through the array
this.jobs.forEach(oneJob, function(value, key) {
console.log(key + ': ' + value);
});
Usage of forEach in AngularJS:
For documentation try to check AngularJS forEach Docs
Syntax:
someIterable.forEach(object, iterator, [context])
Please check below example
class Job {
id: any;
status: any;
constructor(obj: any) {
this.id = obj.id;
this.status = obj.status;
}
}
let arr = [
{
id: 1,
status: "job"
}, {
id: 2,
status: "job2"
}
];
let newArr: any = [];
arr.forEach(a => {
let obj: Job = new Job(a);
newArr.push(obj);
})
console.log(newArr);
newArr.forEach((a: any) => {
console.log(a);
})

Adding an src from an API in Angular7

This is my component.ts where when it's loaded I get the data from the api, which I can see in the console.log, I do infact get my array of 10 objects (they come in groups of 10 on the api). I have the correct path in the API for the source code of the first image in the array of 10 which I typed to out the correct path for in normal http/javascript format of data.hits.hits[n]._source.images[n].urls.original. However when I try to put it in angular it can't read the data value as it is right now since it's out of scope, but I can't figure out how to word it in a better way.
import { Component, OnInit } from '#angular/core';
import { ConfigService } from '../../config.service';
import { Observable } from 'rxjs';
#Component({
selector: 'app-property-binding',
templateUrl: './property-binding.component.html',
styleUrls: ['./property-binding.component.css']
})
export class PropertyBindingComponent implements OnInit {
private isHidden : boolean;
public zeroImage : string;
private Photos : Observable<Object>;
constructor(private configService: ConfigService) { }
ngOnInit() {
//doing the API call
this.Photos = this.configService.getConfig();
this.Photos.subscribe((data) => console.log(data));
}
toggle() : void {
this.isHidden = !this.isHidden;
if(this.isHidden){
//var zeroImg = document.createElement("img");
this.zeroImage.src = data.hits.hits[0]._source.images[0].urls.original;
}
}
}
Here is the Angular html page that should property bind the src with the variable that I want.
<p>
View Artworks
</p>
<button class="btn btn-info" (click)="toggle()">Show Artwork</button>
<div class="col-md-4" *ngIf="isHidden">
<img [src]="zeroImage">
</div>
Here is the service method that I have the method that makes the API call
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ConfigService {
private httpOptions = {
headers: new HttpHeaders({
'ApiKey': 'my_personal_key'
})
};
private configUrl = 'https://api.art.rmngp.fr/v1/works';
constructor(private http: HttpClient) { }
getConfig(){
let obs = this.http.get(this.configUrl, this.httpOptions)
console.log("Inside the getConfig method, before subscribe, doing API call" +
obs);
//might not need to subscribe here??
//obs.subscribe((response) => console.log(response))
return obs;
//return this.http.get(this.configUrl, this.httpOptions);
}
}
And slightly unrelated code, this is the normal http/javascript where I wrote the code Outside of Angular, which works perfectly fine.
function displayPhoto(){
fetch('https://api.art.rmngp.fr/v1/works/, {headers: {ApiKey: "my_personal_key"}})
.then(function(response){
return response.json();
})
.then(function(data){
document.getElementById("zeroImg").src = data.hits.hits[0]._source.images[0].urls.original;
Again, the API call in Angular works, I can see I am pulling the data successfully, I however can not set the image to the first image in the set of data and have been struggling with it. any help will help
You are not doing anything with the data when you subscribe
this.Photos.subscribe((data) => console.log(data));
You have not done anything with the data here.
zeroImg.src = data.hits.hits[0]._source.images[0].urls.original;
zeroImg is a string and makes no sense to set a src property on it and data is undefined at the point. The only place there is a data variable is in your subscription function but it is not available here.
The following will set the src of the image
this.Photos.subscribe((data) => {
this.zeroImg = data.hits.hits[0]._source.images[0].urls.original;
});
Make the toggle function just toggle the isHidden flag and get rid of the rest.
ngOnInit() {
//doing the API call
this.Photos = this.configService.getConfig();
this.Photos.subscribe((data) => {
this.zeroImg = data.hits.hits[0]._source.images[0].urls.original;
});
}
toggle() : void {
this.isHidden = !this.isHidden;
}

Angular 2 - Call a function that exists outside of the current class

I want to call a function that exists in HomePage class which is outside of the (class Popover) that I want to use the function on, I've already done some research, and I guess that I need to do something like dependency injection, I've tried to follow some tutorials but I was not lucky enough to solve the issue.
Popover class:
#Component({
template: `
<div>
<button ion-item *ngFor="let city of cities" (click)="switchToThisCity(city.cityName);close();">{{city.cityName | uppercase}}</button>
</div>
`
})
class MyPopover{
static get parameters(){
return [[Http], [ViewController]];
}
constructor(http, viewCtrl) {
this.http = http;
this.viewCtrl = viewCtrl;
//Async Call
var getCities = new URLSearchParams();
this.http.get('https://restApi.com/class/outlet', {headers: ParseHeaders}).subscribe(data => {
this.cities = data.json().results;
});
///
}
close() {
this.viewCtrl.dismiss();
}
switchToThisCity(currentCity){
//I WANT TO CALL THIS FUNCTION WHICH EXISTS ON HomePage CLASS
return getQueries(currentCity);
}
}
HomePage Class:
#Component({
templateUrl: 'build/pages/home/home.html',
})
export class HomePage {
static get parameters(){
return [[NavController],[Http], [NavParams]];
}
// this.cartLength = this.cart.items.length;
constructor() {}
//I NEED TO USE THIS IN THE POPOVER CLASS
getQueries(city){
var cities = new URLSearchParams();
cities.set('cityName', city);
this.http.get('https://restApi.com/classes/citiesList', { search : dishesParams, headers: ParseHeaders}).subscribe(data => {
this.getCities = data.json().results;
});
}
}
Create a Service class
cities.service
#Injectable()
export class CitiesService {
getQueries(city) {
var cities = new URLSearchParams();
cities.set('cityName', city);
return this.http.get('https://restApi.com/classes/citiesList', {
search: dishesParams,
headers: ParseHeaders
}) // here we return an observable so we can subscribe to it in our class
}
and in Popover: (Same with homepage class)
export class MyPopover{
constructor(private citiesService:CitiesService) {
}
// and this is how you use the function
this.citiesService.getQueries().subscribe(data => {
this.getCities = data.json().results;
});
}
UPDATE : have a look at this article: http://nicholasjohnson.com/blog/how-to-do-everything-in-angular2-using-es6/
First up, anything is injectable in Angular, so PetService can be just a newable function.
The Angular DI mechanism will automatically use it to create a
singleton that is local to the correct branch of the injector tree. If
you only have a root injector (made automatically by Angular 2 on
bootstrap), this will be a global singleton, just like Angular
the principle here is to create a service that handles the request and inject it, return an observable object and subscribe, then you can do whatever you want with the response...
I would extract the getQueries method into a service:
#Injectable()
export class QueryService {
constructor(http) {
this.http = http;
}
static get parameters(){
return [[Http]];
}
}
and inject it into both components:
#Component({
templateUrl: 'build/pages/home/home.html',
providers: [ QueryService ]
})
export class HomePage {
static get parameters(){
return [[NavController],[NavParams], [QueryService];
}
constructor(nav, params, service) {
this.service = service;
}
getQueries(city){
this.service.getQueries(city)...
}
}
and the same in the MyPopover class.

Categories

Resources