Cannot read property 'create' of undefined' from Toast in Ionic - function

I have this code:
import { Component } from '#angular/core';
import {NavController } from 'ionic-angular';
import * as firebase from 'firebase';
import firebase_admin from 'firebase';
import {LoginPage} from '../login/login';
import { RegisterPage } from '../register/register';
import { Diagnostic } from '#ionic-native/diagnostic';
import { ToastController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
static get parameters() {
return [[NavController]];
}
constructor(public navCtrl: NavController, public diagnostic: Diagnostic, public toastCtrl: ToastController) {
this.navCtrl = navCtrl;
this.toastCtrl = toastCtrl;
}
openAddPage() {
let successCallback = (isAvailable) => { this.navCtrl.push(LoginPage)
};
let toast = this.toastCtrl.create({
message: 'Test',
duration: 3000,
position: 'top'
});
this.diagnostic.isLocationAvailable().then(successCallback).catch(toast.present);
}
}
When I click on the Log-In button in my html file, it runs (openAddPage).
When I do so I get the following error:
TypeError: Cannot read property 'create' of undefined
What is the issue?

Related

When using Json file in angular it throws 404 error?

import { Component, OnInit } from '#angular/core';
import { Players } from './players'
import { HttpClient } from '#angular/common/http'
#Component({
selector: 'app-json-with-search',
templateUrl: './json-with-search.component.html',
styleUrls: ['./json-with-search.component.scss']
})
export class JsonWithSearchComponent implements OnInit {
player: Players[];
constructor( private http:HttpClient) { }
ngOnInit(): void {
this.http.get('/sample.json').subscribe((result)=> {
//this.player = result;
console.log(result)
}, (error)=> {
console.log(error)
})
}
}
this is my code
i tried to get data from local json file but it returns 404 error
can anybody help me to solve this issue?

Migrating from Ionic 3 to Ionic 5 - Json functions on user-data

Hello i am trying to migrate from Ionic Cordova 3 to 5.
I want to put a call a php function to get results. PHP works fine.
this is what i did to call the results.
home.ts
allMediaSet(){
console.log('dddd1');
this.offset = 0;
this.userData.allMedias(this.offset)
.map(res => res.json())
.subscribe(data => {
if (data.success) {
this.allMedia = data.mediaFeed;
}
});
}
user-data.ts function
allMedias(offset: number) {
console.log('ddd');
let url = this.appData.getApiUrl() + 'allMedia';
let data = this.jsonToURLEncoded({
api_signature: this.api_signature,
offset: offset
});
return this.http.post(url, data, this.options);
}
this is the error i am getting
core.js:6014 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[Platform]:
StaticInjectorError(Platform: core)[Platform]:
NullInjectorError: No provider for Platform!
NullInjectorError: StaticInjectorError(AppModule)[Platform]:
StaticInjectorError(Platform: core)[Platform]:
NullInjectorError: No provider for Platform!
app.module.ts
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { InAppBrowser } from '#ionic-native/in-app-browser/ngx';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { IonicModule } from '#ionic/angular';
import { IonicStorageModule } from '#ionic/storage';
import { Platform} from 'ionic-angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ServiceWorkerModule } from '#angular/service-worker';
import { environment } from '../environments/environment';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
BrowserModule,
AppRoutingModule,
Platform,
HttpClientModule,
FormsModule,
IonicModule.forRoot(),
IonicStorageModule.forRoot(),
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: environment.production
})
],
declarations: [AppComponent],
providers: [InAppBrowser, SplashScreen, StatusBar],
bootstrap: [AppComponent]
})
export class AppModule {}
login.ts (has the results i want to return)
import { Component } from '#angular/core';
import { NgForm } from '#angular/forms';
import { Router } from '#angular/router';
import { UserData } from '../../providers/user-data/user-data';
import { UserOptions } from '../../interfaces/user-options';
#Component({
selector: 'page-login',
templateUrl: 'login.html',
styleUrls: ['./login.scss'],
})
export class LoginPage {
resposeData: any;
loginData: any = {};
allMedia:any =[];
mediaType:string = '';
offset: number = 0;
login: UserOptions = { username: '', password: '' };
submitted = false;
constructor(
public userData: UserData,
public router: Router,
)
{
this.allMediaSet();
}
allMediaSet(){
console.log('dddd1');
this.offset = 0;
this.userData.allMedias(this.offset)
.subscribe(data => {
console.log(data);
});
}
onLogin(form: NgForm) {
this.submitted = true;
if (form.valid) {
this.userData.login(this.login.username);
this.router.navigateByUrl('/app/tabs/schedule');
}
}
}
any help?
Your question seems like not Ionic specific but it is about Angular. Since good old Ionic 3 / Angular 4 days, Angular moved on from Http to HttpClient.
Please see here: https://angular.io/guide/http#setup
You need to ensure you migrate your Angular code to use the latest HttpClientModule:
https://devops.datenkollektiv.de/migrating-from-angular-httpmodule-to-new-angular-43-httpclientmodule.html
In short:
replace 'Http' with 'HttpClient':
import {Http} from '#angular/http';
becomes
import { HttpClient } from '#angular/common/http';
Remove manual extraction of JSON via map operator:
this.userData.allMedias(this.offset).map(res => res.json())
becomes
this.userData.allMedias(this.offset)

Angular 9 Parent Child Call Function

My parent component call function on two childs components.
I have an error on the second component.
Parent Component
import { Component, Input, ViewChild } from '#angular/core';
import { EchartsAreaStackComponent } from './echart/echarts-area-stack.component';
import { AccordionComponent } from './accordion/accordion.component';
#Component({
selector: 'hg-waitstats',
styleUrls: ['./waitStats.component.scss'],
templateUrl: './waitStats.component.html',
})
export class WaitStatsComponent {
#ViewChild(EchartsAreaStackComponent) EchartsAreaStackComponent: EchartsAreaStackComponent ; //work
#ViewChild(AccordionComponent) AccordionComponent: AccordionComponent ; //not work
#Input() selectedLimit: String = '3';
ngAfterViewInit() {
// child is set
this.EchartsAreaStackComponent.changeLimit(this.selectedLimit); // work
this.AccordionComponent.getWaitStatData(this.selectedLimit); // not work
}
changeLimit(limit: any){
this.EchartsAreaStackComponent.changeLimit(limit); //work
this.AccordionComponent.getWaitStatData(limit); // not work
}
}
parent html
<div class="col-6">
<nb-card>
<nb-card-header>
<nb-select [selected]="selectedLimit" (selectedChange)="changeLimit($event)">
<nb-option value="5">Top 5</nb-option>
<nb-option value="3">Top 3</nb-option>
<nb-option value="1">Top 1</nb-option>
</nb-select>
</nb-card-header>
<nb-card-body>
<ngx-echarts-area-stack></ngx-echarts-area-stack>
</nb-card-body>
</nb-card>
</div>
Working component (EchartsAreaStackComponent)
import { AfterViewInit, Component, OnDestroy } from '#angular/core';
import { NbThemeService } from '#nebular/theme';
import { WaitStatsService } from '../../../../#core/backend/common/services/waitStats.service';
import { WaitType } from '../../../../#core/interfaces/common/waitStats';
import { UserStore } from '../../../../#core/stores/user.store';
import { User } from '../../../../#core/interfaces/common/users';
#Component({
selector: 'ngx-echarts-area-stack',
templateUrl: './echarts-area-stack.component.html',
styleUrls: ['./echarts-area-stack.component.scss'],
providers:[WaitStatsService]
})
export class EchartsAreaStackComponent implements AfterViewInit, OnDestroy {
options: any = {};
themeSubscription: any;
user: User;
legendData: WaitType[];
seriesData: {};
seriesX: {};
selectedLimit: String = '3';
constructor(
private theme: NbThemeService,
private service: WaitStatsService,
private userStore: UserStore
) {}
ngOnInit()
{
this.getWaitStatData(this.selectedLimit);
}
getWaitStatData(limit){
...
}
changeLimit(limit) {
if (this.selectedLimit !== limit) {
this.selectedLimit = limit;
this.getWaitStatData(this.selectedLimit);
}
}
ngAfterViewInit() {
...
}
ngOnDestroy(): void {
this.themeSubscription.unsubscribe();
}
}
Component that genere error (AccordionComponent)
import { Component } from '#angular/core';
import { WaitStatsCategoriesService } from '../../../../#core/backend/common/services/waitStatsCategories.service';
#Component({
selector: 'ngx-accordion',
templateUrl: 'accordion.component.html',
styleUrls: ['accordion.component.scss'],
providers:[WaitStatsCategoriesService]
})
export class AccordionComponent {
accordion;
selectedLimit: String = '3';
waitTypes: {};
constructor(
private service: WaitStatsCategoriesService
) {}
toggle() {
this.accordion.toggle();
}
ngOnInit()
{
this.getWaitStatData(this.selectedLimit);
}
getWaitStatData(limit){
this.service.getTopWaitType( limit )
.subscribe( (data) => {
this.waitTypes = data.waitTypes;
});
}
}
ERROR TypeError: Cannot read property 'getWaitStatData' of undefined
at WaitStatsComponent.ngAfterViewInit (:4200/app-pages-pages-module.js:208942)
at callHook (:4200/vendor.js:40119)
at callHooks (:4200/vendor.js:40083)
at executeInitAndCheckHooks (:4200/vendor.js:40024)
at refreshView (:4200/vendor.js:46856)
at refreshDynamicEmbeddedViews (:4200/vendor.js:48145)
at refreshView (:4200/vendor.js:46803)
at refreshComponent (:4200/vendor.js:48220)
at refreshChildComponents (:4200/vendor.js:46511)
at refreshView (:4200/vendor.js:46832)
You haven't add ngx-accordion in parent.html template. Thats why its breaking. Other component working as its available in your parent.html

Error property undefined in angular

I have a HTMLElement type initialized at the beginning of my component class like this:
My component class:
import { Component, AfterViewInit, Renderer, ElementRef, OnInit} from '#angular/core';
import { NgbActiveModal } from '#ng-bootstrap/ng-bootstrap';
import { Router } from '#angular/router';
import { JhiEventManager } from 'ng-jhipster';
#Component({
selector: 'jhi-login-modal',
templateUrl: './login.component.html'
})
export class JhiLoginModalComponent implements AfterViewInit, OnInit {
domElement: HTMLElement;
constructor(
private login1: ElementRef
) {
}
ngOnInit() {
this.accessDomElement();
}
accessDomElement() {
this.domElement = this.login1.nativeElement.querySelector(`#login123`);
}
My testing class:
import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '#angular/core/testing';
describe('LoginComponent', () => {
let comp: JhiLoginModalComponent;
let fixture: ComponentFixture<JhiLoginModalComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
............
}));
beforeEach(() => {
fixture = TestBed.createComponent(JhiLoginModalComponent);
comp = fixture.componentInstance;
....
});
//MY TEST
it ('The form login should have the field Nombre', async(() => {
console.log('lalalalla' + comp.domElement);
expect(comp.domElement.innerHTML).toContain('Login');
}));
Now I want to test the domElement in a testing class.
But it returns undefined when I print domElement.
My html eleemnt:
<label id="login123" for="username" jhiTranslate="global.form.username">Login</label>
I want to test THIS ELEMENT DOMeLEMET WHICH IS OF TYPE HTMLELEMENT.
Do I make an error in injection?? Because it gives me this error:
Cannot read prperty innerHTMLof undefined and outputs undefined in console.

Console.log to html element - Angular 4

Simple question. I have the following response from web service and I am observing it on chrome console. How do I deploy this onto Html element in angular 4? I tried to convert into JSON, but I encountered with another problem so I just decided to go with what I received after parseString.
All I want to do is, to display those fields in html element using Angular. For now, I just have component.ts file and trying to do something in html but can't figure out.
import { HttpClient, HttpErrorResponse, HttpHeaders } from '#angular/common/http';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { Observable } from 'rxjs/Observable';
import { RequestOptions, Response } from '#angular/http';
import { Injectable } from '#angular/core';
import { parseString } from 'xml2js'
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
//import { IMovie } from './movie';
#Injectable()
export class AppService {
private urlNorth = 'service';
constructor(private http: HttpClient) { }
getMovies(): Observable<any[]> {
const headers = new HttpHeaders();
headers.set('Content-Type', 'text/sml');
headers.set('Accept', 'text/xml');
headers.set('Content-Type', 'text/xml');
return this.http.get<any[]>(this.urlNorth, { headers })
.map(res => {
var result = res.text().replace('<string xmlns="service">', '').replace('</string>', '').replace(/</g, '<').replace(/>/g, '>');
parseString(result, (err, resultN) => {
if (err) {
return console.dir('invalid XML');
}
else {
console.log(resultN);
}
})
})
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse): ErrorObservable {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
const errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}
Log data
This code:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
Does not belong in your service file. This is a component decorator and it should be on your component. Like this:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _appService: AppService) { }
getProduction() {
this._appService.getProduction()
}
}
Then your index.html file should use the tag to display the HTML.
In looking at your code more closely, there are other issues as well. For example, you are calling getProduction two times. You should not be calling it from the service constructor.
Also, the subscribe should be in the component, not the service.
And you should be using Http OR HttpClient, not both.
And TestBed is only for use in tests ... not in services.
I have a more complete example of a working component/service here: https://github.com/DeborahK/Angular-GettingStarted in the APM-Final folder. Consider looking through that code (or starting with that code) and making adjustments as needed for your application.
Here is a working service. (Without a plunker I can't successfully show this with your code. So you will need to make the appropriate replacements for your example.)
Service
import { Injectable } from '#angular/core';
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { IMovie } from './movie';
#Injectable()
export class MovieService {
private moviesUrl = './api/movies/movies.json';
constructor(private http: HttpClient) { }
getMovies(): Observable<IMovie[]> {
return this.http.get<IMovie[]>(this.moviesUrl)
.do(data => console.log(JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(err: HttpErrorResponse): ErrorObservable {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
const errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}
Component:
import { Component, OnInit } from '#angular/core';
import { IMovie } from './movie';
import { MovieService } from './movie.service';
#Component({
templateUrl: './movie-list.component.html',
styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit {
movies: IMovie[];
errorMessage: string;
constructor(private movieService: MovieService) { }
ngOnInit(): void { this.getMovies(); }
getMovies(): void {
this.movieService.getMovies()
.subscribe(
(movies: IMovie[]) => this.movies = movies,
(error: any) => this.errorMessage = <any>error);
}
}