Angular Interceptors not working in angular 5 version - angular-http-interceptors

I am also getting the same error , NO provider for the class
AppHttpInterceptor even i added the provider in the app module and done every small thing to get it worked.
Please go through the code
http.interceptor.ts
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '#angular/common/http';
import { Injectable } from "#angular/core"
import { Observable } from "rxjs";
import { tap, catchError } from "rxjs/operators";
import { ToastrService } from 'ngx-toastr';
import { of } from 'rxjs/observable/of';
#Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) { }
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log('start')
return next.handle(req).pipe(
tap(evt => {
console.log(evt);
alert();
if (evt instanceof HttpResponse && evt.body && evt.body.success) {
this.toasterService.success(evt.body.success.message, evt.body.success.title, { positionClass: 'toast-bottom-center' });
}
}),
catchError((err: any) => {
console.log('err')
if (err instanceof HttpErrorResponse) {
try {
this.toasterService.error(err.error.message, err.error.title, { positionClass: 'toast-bottom-center' });
} catch (e) {
this.toasterService.error('An error occurred', '', { positionClass: 'toast-bottom-center' });
}
//log error
}
return of(err);
}));
}
}
role.service.ts
import { AppHttpInterceptor } from './http.interceptor';
import { Injectable } from '#angular/core';
import { Headers, Http, RequestOptions, Response } from "#angular/http";
import { environment } from '../../environments/environment';
#Injectable()
export class RolesService {
private apiUrl = environment.apiUrl
constructor(private http: Http, private ads: AppHttpInterceptor) { }
getRoles() {
let url = this.apiUrl + '/api/v1/role/all';
return this.http.get(url, this.jwt()).map((response: Response) => {
//console.log('service', response)
// this.ads.displayToast(response.json());
return response;
});
}
}
}
I have added the provider for the hTTp Interceptors in the app module as below
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { ThemeComponent } from './theme/theme.component';
import { LayoutModule } from './theme/layouts/layout.module';
import { BrowserAnimationsModule } from "#angular/platform-browser/animations";
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ScriptLoaderService } from "./_services/script-loader.service";
import { ThemeRoutingModule } from "./theme/theme-routing.module";
import { AuthModule } from "./auth/auth.module";
import { SharedService } from './_services/shared.service';
import { ToastrModule } from 'ngx-toastr';
import { AppHttpInterceptor } from './_services/http.interceptor';
#NgModule({
declarations: [
ThemeComponent,
AppComponent
],
imports: [
LayoutModule,
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
ThemeRoutingModule,
AuthModule,
HttpClientModule,
ToastrModule.forRoot({
timeOut: 2000,
positionClass: 'toast-bottom-right',
preventDuplicates: true,
autoDismiss: true,
newestOnTop: true,
progressBar: true,
closeButton: true,
tapToDismiss: true
}),
],
providers: [ScriptLoaderService, SharedService,
[{
provide: HTTP_INTERCEPTORS, useClass: AppHttpInterceptor, multi: true
}]
],
bootstrap: [AppComponent]
})
export class AppModule { }

Related

Nativescript-angular2 Uncaught (in promise): Error: Cannot match any routes with multiple nested routing

I'm developing a mobile app with nativescript + Angular 8. Basically the app download a fat json object from the backend and then with multiple nested routing give the possibility to select a specific action.
The routing chain (each moduel is the child of the previous) is written below:
app-routing.module.ts -> main-routing.module.ts -> asset-routing.module.ts -> future-state.routing.module.ts
in the main.component.html is rendered a list of selectable assets generated dynamically from the json downloaded. When an asset is clicked a new list of selectable future-state generated dynamically from the json for the specific asset is shown. When a future-state is selected a list of selectable activities generated dynamically from the json for the specific future-state is shown. At the end the user can select the activity and the data is sent back to the backend.
In the selection phase everything is ok until the future-state item selection. When I try to select a future-state the code return me the Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: ....
future-state.commponent.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from "#angular/router";
import { RouterExtensions } from "nativescript-angular/router";
import { GlobalVariablesService } from '../../../_services/global-variables.service';
import { AndonPossibleIssueOpenStateDto } from '../../../_models/andon-possible-issue-open-state-dto';
#Component({
selector: 'ns-future-state',
templateUrl: './future-state.component.html',
styleUrls: ['./future-state.component.css']
})
export class FutureStateComponent implements OnInit {
id: number;
andonPossibleIssueOpenStateDto: AndonPossibleIssueOpenStateDto;
constructor(
private globalVariables: GlobalVariablesService,
private _route: ActivatedRoute,
private _routerExtensions: RouterExtensions
) { }
ngOnInit(): void {
const idFutureState = +this._route.snapshot.params.id;
this._route.params.subscribe(params => { this.id = params['id']; });
//this.andonPossibleIssueOpenStateDto=this.globalVariables.getAndonBotAssetPossibleStateIssueDto().find(function(element){return element.asset.id==idAsset}) as AndonPossibleIssueOpenStateDto;
}
onBackTap(): void {
this._routerExtensions.back();
}
}
future-state.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { FutureStateRoutingModule } from "./future-state-routing.module";
import { FutureStateComponent } from "./future-state.component";
import { ActivityComponent } from "./activity/activity.component";
#NgModule({
imports: [
NativeScriptCommonModule,
FutureStateRoutingModule
],
declarations: [
FutureStateComponent,
ActivityComponent
],
exports: [FutureStateComponent],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class FutureStateModule { }
future-state-routing.module.ts
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { FutureStateComponent } from "./future-state.component";
import { ActivityComponent } from "./activity/activity.component";
const routes: Routes = [
{
path: "",
component: FutureStateComponent
},
{
path: "activity/:id",
component: ActivityComponent
}
];
#NgModule({
imports: [NativeScriptRouterModule.forChild(routes)],
exports: [NativeScriptRouterModule]
})
export class FutureStateRoutingModule { }
asset.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from "#angular/router";
import { RouterExtensions } from "nativescript-angular/router";
import { GlobalVariablesService } from '../../_services/global-variables.service';
import { AndonBotAssetPossibleStateIssueDto } from '../../_models/andon-bot-asset-possible-state-issue-dto';
#Component({
selector: 'ns-asset',
templateUrl: './asset.component.html',
styleUrls: ['./asset.component.css']
})
export class AssetComponent implements OnInit {
id: number;
andonBotAssetPossibleStateIssueDto: AndonBotAssetPossibleStateIssueDto;
constructor(
private globalVariables: GlobalVariablesService,
private _route: ActivatedRoute,
private _routerExtensions: RouterExtensions
) { }
ngOnInit(): void {
const idAsset = +this._route.snapshot.params.id;
this.id = this._route.snapshot.params['id'];
console.log(this._route.snapshot.children);
console.log(this._route.snapshot.routeConfig);
this.andonBotAssetPossibleStateIssueDto=this.globalVariables.getAndonBotAssetPossibleStateIssueDto().find(function(element){return element.asset.id==idAsset}) as AndonBotAssetPossibleStateIssueDto;
console.log(this.andonBotAssetPossibleStateIssueDto.asset);
console.log(this._route.firstChild);
}
onBackTap(): void {
this._routerExtensions.back();
}
}
asset.coponent.html
<ActionBar class="action-bar">
<Label class="action-bar-title" [text]="andonBotAssetPossibleStateIssueDto.asset.name"></Label>
</ActionBar>
<StackLayout class="page page-content">
<ListView [items]="andonBotAssetPossibleStateIssueDto.possibleStateIssueDto.optionStateIssue" class="list-group">
<ng-template let-item="item">
<Label [nsRouterLink]="['./futureState', item.futureState.id]" [text]="item.futureState.name" class="list-group-item"></Label>
</ng-template>
</ListView>
</StackLayout>
asset.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { AssetRoutingModule } from "./asset-routing.module";
import { AssetComponent } from "./asset.component";
import { FutureStateModule } from "./future-state/future-state.module";
#NgModule({
imports: [
NativeScriptCommonModule,
AssetRoutingModule,
FutureStateModule
],
declarations: [
AssetComponent
],
exports: [AssetComponent],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class AssetModule { }
asset-routing.module.ts
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { NSEmptyOutletComponent } from "nativescript-angular";
import { AssetComponent } from "./asset.component";
import { FutureStateComponent } from "./future-state/future-state.component";
const routes: Routes = [
{
path: "",
component: AssetComponent
},
{
path: "futureState/:id",
component: FutureStateComponent
},
{
path: "futureState",
component: NSEmptyOutletComponent,
loadChildren: () => import("~/app/main/asset/future-state/future-state.module").then((m) => m.FutureStateModule)
}
];
#NgModule({
imports: [NativeScriptRouterModule.forChild(routes)],
exports: [NativeScriptRouterModule]
})
export class AssetRoutingModule { }
Below the error message:
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'main/asset/698/futureState/6'
JS: Error: Cannot match any routes. URL Segment: 'main/asset/698/futureState/6'
JS:
at ApplyRedirects.push.../node_modules/#angular/router/fesm5/router.js.ApplyRedirects.noMatchError (file:///node_modules#angular\router\fesm5\router.js:2459:0) [angular]
JS: at CatchSubscriber.selector (file:///node_modules#angular\router\fesm5\router.js:2440:0) [angular]
JS: at CatchSubscriber.push.../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (file:///node_modules\rxjs_esm5\internal\operators\catchError.js:34:0) [angular]
JS: at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (file:///node_modules\rxjs_esm5\internal\Subscriber.js:79:0) [angular]
JS: at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (file:///data/data/org.nativescript.AndonMobile/fil...
The issue was that in the asset.component.html the link requested was /main/asset/[idAsset]/futureState/[idFutureState] instead the router dynamically generated in asset-routing.module.ts was something like /main/asset/futureState/[idFutureState].
I've modified the part:
{
path: "futureState/:id",
component: FutureStateComponent
}
with:
{
path: ":this.id/futureState/:id",
component: FutureStateComponent
}

Ionic 4 native storage - Error storing item Object code: 5, source: "Native", exception: null, stack:

I have this ionic 4 project (Using REST API) and have also install ionic native storage. I might have multiple questions concerning this project, but the first is:
I want to store login data so I can be able to pass a token to the header to be used for other endpoints. But if I run the app and try to login, I get the following error:
Error storing item
Object { code: 5, source: "Native", exception: null, stack: "" }
My auth ts is where my login function is:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { tap } from 'rxjs/operators';
import { ApiService } from './api.service';
import { User } from '../models/user';
import { NativeStorage } from '#ionic-native/native-storage/ngx';
#Injectable({
providedIn: 'root'
})
export class AuthService {
isLoggedIn = false;
token: any;
constructor(
private http: HttpClient,
private api: ApiService,
private storage: NativeStorage
) { }
login(account_number: Number, password: String) {
return this.http.post(this.api.API_URL + '/login',
{account_number: account_number, password: password}
).pipe(
tap(token => {
this.storage.setItem('token', token)
.then(
() => {
console.log('Token Stored', token);
},
error => console.error('Error storing item', error)
);
this.token = token;
this.isLoggedIn = true;
return token;
}),
);
}
register(name: String, email: String, phone: Number, reference: String, account_number: String, password: String) {
return this.http.post(this.api.API_URL + '/register',
{ name: name, email: email, phone: phone, reference: reference, account_number: account_number, password: password }
)
}
logout() {
const headers = new HttpHeaders({
'Authorization': "auth-token" + this.token
});
return this.http.get(this.api.API_URL + '/logout', { headers: headers })
.pipe(
tap(data => {
this.storage.remove("token");
this.isLoggedIn = false;
delete this.token;
return data;
})
)
}
getToken() {
return this.storage.getItem('token').then(
data => {
this.token = data;
if (this.token != null) {
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
},
error => {
this.token = null;
this.isLoggedIn = false;
}
);
}
}
And here is is my login.ts.
import { Component, OnInit } from '#angular/core';
import { ModalController, NavController } from '#ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { AlertService } from 'src/app/services/alert.service';
import { RegisterPage } from '../register/register.page';
import { NgForm } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
userdata: any;
constructor(
private modalC: ModalController,
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService,
// private router: Router
) { }
ngOnInit() {
}
// Dismiss Login Modal
dismissLogin() {
this.modalC.dismiss();
}
// On Register button tap, dismiss login modal and open register modal
async registerModal() {
this.dismissLogin();
const registerModal = await this.modalC.create({
component: RegisterPage
});
return await registerModal.present();
}
login(form: NgForm) {
this.authService.login(form.value.account_number, form.value.password).subscribe(
data => {
this.userdata = data;
this.alertService.presentToast("Logged In");
console.log('this is loggin in userdata', data, "and this is the stored auth-token", this.userdata.message);
},
error => {
console.log(error, "logged in");
},
() => {
this.dismissLogin();
this.navCtrl.navigateRoot('/dashboard');
console.log('this is this.userdata', )
}
);
}
}
Here is aslo my app.module.ts
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy, } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '#angular/common/http';
import { NativeStorage } from '#ionic-native/native-storage/ngx';
#NgModule({
declarations: [
AppComponent,],
entryComponents: [
],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule
],
providers: [
StatusBar,
SplashScreen,
NativeStorage,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
You can simply use javascript local storage and also use Ionic native storge for your purpose.
Mostly is used localStorage.set(). In case just want to store strings.
u also use Ionic native storage for the object and many things.
https://ionicframework.com/docs/native/native-storage

Ionic 4 storage problem : No provider for Storage

I try to import storage mdule in my ionic project. but when i add providers Storage, The erro is changed. The error become 'can't resolved storege all : (?)'
How can i solve this error? can you help me please?
I wrote my codes below.
I watch this video :https://www.youtube.com/watch?v=h_IhS8QQjUA&list=PLNFwX8PVq5q7S-p_7zO99xdauhDsnMPw0&index=17&t=0s
App Module ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import {Storage} from '#ionic/storage';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,IonicStorageModule.forRoot()],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Page TS
import { Component, ViewChild } from "#angular/core";
import { StorageService, Item } from "../services/storage.service";
import { Platform, ToastController, IonList } from "#ionic/angular";
#Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"]
})
export class HomePage {
items: Item[] = [];
newItem: Item = <Item>{};
#ViewChild("mylist") mylist: IonList;
constructor(
private storageService: StorageService,
private plt: Platform,
private toastController: ToastController
) {
this.plt.ready().then(() => {
this.loadItems();
});
}
loadItems() {
this.storageService.getItems().then(items => {
this.items = items;
});
}
addItem() {
this.newItem.modified = Date.now();
this.newItem.id = Date.now();
this.storageService.addItem(this.newItem).then(item => {
this.newItem = <Item>{};
this.showToast("Item Added");
this.loadItems();
});
}
updateItem(item:Item){
item.title='UPDATED:${item.title}';
item.modified=Date.now();
this.storageService.updateItem(item).then(item=>{
this.showToast("Item Updated");
this.loadItems();
});
}
deleteItem(item:Item){
this.storageService.deleteItem(item.id).then(item=>{
this.showToast("Item Deleted");
this.mylist.closeSlidingItems();
this.loadItems();
});
}
async showToast(msg){
const toast=await this.toastController.create({
message:msg,
duration:2000
});
toast.present();
}
}
Service
import { Injectable } from '#angular/core';
export interface Item{
id:number,
title:string,
value:string,
modified:number
}
const ITEMS_KEY="my-items";
#Injectable({
providedIn: 'root'
})
export class StorageService {
constructor(private storage:Storage) { }
addItem(item:Item):Promise<any>{
return this.storage.get(ITEMS_KEY).then((items:Item[])=>{
if(items){
items.push(item);
return this.storage.set(ITEMS_KEY,items);
}else{
return this.storage.set(ITEMS_KEY,[item]);
}
});
}
getItems():Promise<Item[]>{
return this.storage.get(ITEMS_KEY);
}
getItem(id:number){
}
updateItem(item:Item):Promise<any>{
return this.storage.get(ITEMS_KEY).then((items:Item[])=>{
if(!items || items.length==0){
return null;
}
let newItems:Item[]=[];
for (let i of items){
if(i.id==item.id){
newItems.push(item);
}else{
newItems.push(i);
}
}
return this.storage.set(ITEMS_KEY,newItems);
});
}
deleteItem(id:number):Promise<Item>{
return this.storage.get(ITEMS_KEY).then((items:Item[])=>{
if(!items || items.length==0){
return null;
}
let toKeep:Item[]=[];
for (let i of items){
if(i.id!=id){
toKeep.push(i);
}else{
//newItems.push(i);
}
}
return this.storage.set(ITEMS_KEY,toKeep);
});
}
}
In the StorageService file, you're injecting the storage like this:
constructor(private storage: Storage) { }
but I cannot see the Storage being imported in that file. So the Storage class injected in the constructor refers to the Web Storage API and not to the Ionic's Storage.
To fix that, please import the Storage from #ionic/storage:
import { Storage } from '#ionic/storage';
// ...
#Injectable({
providedIn: 'root'
})
export class StorageService {
constructor(private storage: Storage) { }
// ...
}
installing
npm install #ionic/storage
npm install #ionic/storage-angular
remember create your storage in the service
import { Storage } from '#ionic/storage';
constructor(private storage:Storage){
this.storage.create();
}
and import this in app.module
import { IonicStorageModule } from '#ionic/storage-angular';
import { Storage } from '#ionic/storage';
with storage in your providers
providers: [{ provide: RouteReuseStrategy},Storage],
ionic-storage angular

HTTP GET Request using ionic 3?

I am new to ionic i am trying to fetch result using REST API , with GET Method but not successfull , I am stuck into this problem from the last two days
can anyone please help me.
My code is here
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Slides } from 'ionic-angular';
import { ViewChild } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Http } from '../../../node_modules/#angular/http';
import { HttpHeaders } from '#angular/common/http';
import { Headers } from '#angular/http';
import { RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map'
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Accept', 'application/json');
headers.append('Authorization', 'Basic Ok9AYWNsZUAxMjM=');
headers.append('AuthUser', '78909890');
headers.append('SecretKey','a8658f0d67890459');
let options = new RequestOptions({ headers: headers });
this.http.get('https:I/v01/?=AttachmentFiles')
.map(res => res.json())
.subscribe(data =>
{
this.posts = data["value"];
console.log('GET RESPONSE',this.posts +"");
});
i am getting error
core.js:1449 ERROR Error: Uncaught (in promise): Error:
StaticInjectorError(AppModule)[ommunicationPage -> Http]:
StaticInjectorError(Platform: core)[ommunicationPage -> Http]:
NullInjectorError: No provider for Http! Error: StaticInjectorError(AppModule)[mmunicationPage -> Http]:
StaticInjectorError(Platform: core)[mmunicationPage -> Http]:
My App Module.ts
import { NgModule, ErrorHandler, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { LoginPage } from '../pages/login/login';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { DashboardPage } from '../pages/dashboard/dashboard';
import { AppDashboardPage } from '../pages/app-dashboard/app-dashboard';
import { WorkHistoryPage } from '../pages/work-history/work-history';
import { ElBalancePage } from '../pages/el-balance/el-balance';
import { LearningTabPage } from '../pages/learning-tab/learning-tab';
import { MandatoryTrainigsPage } from '../pages/mandatory-trainigs/mandatory-trainigs';
import { PastDueTrainingsPage } from '../pages/past-due-trainings/past-due-trainings';
import { ActiveTrainigsPage } from '../pages/active-trainigs/active-trainigs';
import { ChartsModule } from 'ng2-charts';
import { TabsPage } from '../pages/tabs/tabs';
import { BasicDetailsPage } from '../pages/basic-details/basic-details';
import { PersonalDetailsPage } from '../pages/personal-details/personal-details';
import { HomePage } from '../pages/home/home';
import { MangerViewPage } from '../pages/manger-view/manger-view';
import { Navbar } from 'ionic-angular';
import { SuperTabsModule } from 'ionic2-super-tabs';
import { Logger } from 'angular2-logger/core';
import { RestApiProvider } from '../providers/rest-api/rest-api';
import { InAppBrowser } from '#ionic-native/in-app-browser';
import {HelpmetModalPage} from '../pages/helpmet-modal/helpmet-modal';
import {HelpMatePage} from '../pages/help-mate/help-mate';
import {SoftLoanPage} from '../pages/soft-loan/soft-loan';
#NgModule({
declarations: [
MyApp,
DashboardPage,
LoginPage,
AppDashboardPage,
WorkHistoryPage,
ElBalancePage,
LearningTabPage,
MandatoryTrainigsPage,
PastDueTrainingsPage,
ActiveTrainigsPage,
TabsPage,
BasicDetailsPage,
PersonalDetailsPage
],
imports: [
BrowserModule,
HttpClientModule,
ChartsModule,
FormsModule,
SuperTabsModule,
IonicModule.forRoot(MyApp, { tabsPlacement: 'top', }),
SuperTabsModule.forRoot()
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
LoginPage,
DashboardPage,
AppDashboardPage,
WorkHistoryPage,
ElBalancePage,
LearningTabPage,
MandatoryTrainigsPage,
PastDueTrainingsPage,
CorpCommunicationPage
],
providers: [
StatusBar,
SplashScreen,
Logger,
RestApiProvider,
InAppBrowser,
Deeplinks,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
})
export class AppModule { }
Please Help me
Thanks in Advance.
You should import HttpModule in app.module.ts like
import { HttpModule } from '#angular/http';
...
imports: [
HttpModule,
],
If you are using HttpClient then why you have also imported Http from #angular/http?
import { HttpClient } from '#angular/common/http';
constructor(public http: HttpClient) {}
Use this HttpClient for get request. It will work.
I think you don't have to import so many things in your app,module.ts.
Example Http Get:
import { Http, Headers } from '#angular/http';
Don't import HttpClient and HttpHeaders
getSomething(){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Authorization', this.someToken);
headers.append('Something', this.somethingElse);
this.http.get('URL', {headers: headers})
.map(res => res.json())
.subscribe(data => {
resolve(data);
}, (err) => {
reject(err);
});
});
}
And you call it like this:
this.someServiceWithMethod.getSomething().then((data) => {
this.something = data;
}, (err) => {
console.log("something went wrong");
});
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
export class YourComponent {
constructor(private http: HttpClient) {}
YourMethod(name) {
const params = new HttpParams().set('name',name);
const httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/json' },
)
};
this.http.get(GET_API_URL , { params: params }, httpOptions).subscribe(res => {
console.log(JSON.stringify(res, null, 2));
});
}
}
Best practise : Define api calls in a separate Service Class.

IONIC 2 Cloud Push Not Working - App Crashes

I have created IONIC 2 App and at the final stage I am trying to implement the IONI Cloud Push but it is not working and every time App crashing whenever I enable the cloud push register function:
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
I am running the build using 'ionic run android' in my real device
Please help me what i am doing wrong. have checked many articles everywhere it says same process what I have already implemented:-
npm install #ionic/cloud-angular --save
cordova plugin add phonegap-plugin-push --variable SENDER_ID=12341234 --save
ionic io init
and all other configurations.
Below is my app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform, ToastController } from 'ionic-angular';
import { Events } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { Storage } from '#ionic/storage';
import { TabsComponent } from '../pages/tabs/tabs-component/tabs.component';
import { LoginComponent } from '../pages/login/login-component/login.component';
import { Push, PushToken } from '#ionic/cloud-angular';
//import { Push } from 'ionic-native';
//import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
//import { Push, PushObject, PushOptions } from "#ionic-native";
#Component({
templateUrl: './app.html',
})
export class BanglaliveApp {
#ViewChild(Nav) nav: Nav;
rootPage = TabsComponent;
user: any;
pages: Array<{title: string, component: any, category: any}>;
constructor(
public push: Push,
public platform: Platform,
private storage: Storage,
private toastController: ToastController,
public events: Events
) {
this.initializeApp();
events.subscribe('userloggedin', user => {
if(user){
this.user = user;
}
});
storage.get('wordpress.user').then((value) => {
if (value) {
this.user = value;
}
});
this.pages = [
{ title: '????? ????', component: TabsComponent, category: { class:'home' }},
{ title: '?????????', component: LoginComponent, category: {class: 'category'}}
];
}
initializeApp() {
this.platform.ready().then(() => {
// Enable RTL Support
// this.platform.setDir('rtl', true);
StatusBar.styleDefault();
Splashscreen.hide();
// ############## P U S H ###############
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
// this.push.rx.notification()
// .subscribe((msg) => {
// alert(msg.title + ': ' + msg.text);
// });
// ############## P U S H ###############
});
}
openPage(page, index) {
//check if page or post has been called
this.nav.setRoot(page.component);
}
}
login(){
this.nav.push(LoginComponent);
}
logout() {
this.user = undefined;
this.storage.remove('wordpress.user');
this.nav.setRoot(LoginComponent);
}
profile() {
this.nav.push(ProfilePage);
}
}
and here is my app.module.ts:-
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { SharedModule } from './shared/shared.module'
import { TabsModule } from '../pages/tabs/tabs.module';
import { SignUpModule } from '../pages/signup/signup.module'; //SSSS
import { ProfileModule } from '../pages/profile/profile.module'; //SSSS
import { MyApp} from './app.component';
import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'XXXXXX',
},
'push': {
'sender_id': 'XXXXXXXX',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true
},
'android': {
'iconColor': '#343434'
}
}
}
};
#NgModule({
declarations: [
MyApp
],
imports: [
IonicModule.forRoot(MyApp, {
backButtonIcon: 'arrow-back'
}),
CloudModule.forRoot(cloudSettings),
SharedModule,
TabsModule,
SignUpModule,
ProfileModule,
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
Please help..!!
Thanks
It's working perfectly fine for me on real device.
Play with Git Repo.
app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { Push, PushToken } from '#ionic/cloud-angular';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any = HomePage;
constructor(platform: Platform, public push: Push) {
platform.ready().then(() => {
this.push.register().then((t: PushToken) => {
return this.push.saveToken(t);
}).then((t: PushToken) => {
console.log('Token saved:', t.token);
});
this.push.rx.notification()
.subscribe((msg) => {
alert(msg.title + ': ' + msg.text);
});
});
}
}
app.module.ts
import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
const cloudSettings: CloudSettings = {
'core': {
'app_id': '525f53a4'
},
'push': {
'sender_id': '837506444622',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true
},
'android': {
'iconColor': '#343434'
}
}
}
};
#NgModule({
declarations: [
],
imports: [
CloudModule.forRoot(cloudSettings)
],
bootstrap: [IonicApp],
entryComponents: [
],
providers: [
]
})
export class AppModule { }
Finally I found the outdated cordova splash plugin was causing this error and reinstall was not upgrading because in config.xml had the old version of the plugin.
I just deleted the plugin and removed lines from config.xml and reinstalled and it worked.
Just in case it may work for someone else also.