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.
Related
I have several components (about,service,dashboard, etc) in which a header component is added. The application is running fine. However, I am getting errors when testing.
import { Component } from '#angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '#angular/core/testing';
import { IonicModule } from '#ionic/angular';
import { SettingsPage } from './settings.page';
describe('SettingsPage', () => {
let component: SettingsPage;
let fixture: ComponentFixture<SettingsPage>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ SettingsPage,MockHeaderComponent ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(SettingsPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
#Component({
selector: 'app-header',
template: ''
})
class MockHeaderComponent {
}
First Error
Chrome 93.0.4577.82 (Windows 10): Executed 22 of 26 (1 FAILED) (0 secs / 5.88 secs)
ERROR: 'NG0303: Can't bind to 'headline' since it isn't a known property of 'app-header'.'
headline is a variable that I declared in my header component and use in my components to give me the correct title.
Of course, I already looked for solutions on the Internet and came across the following Stack Overflow post: Unit test Angular with Jasmine and Karma, Error:Can't bind to 'xxx' since it isn't a known property of 'xxxxxx'.
Therefore, I have imported and declared my HeaderComponent.
import { Component } from '#angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '#angular/core/testing';
import { IonicModule } from '#ionic/angular';
import { HeaderComponent } from '../header/header.component';
import { SettingsPage } from './settings.page';
describe('SettingsPage', () => {
let component: SettingsPage;
let fixture: ComponentFixture<SettingsPage>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ SettingsPage,HeaderComponent,MockHeaderComponent ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(SettingsPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
#Component({
selector: 'app-header',
template: ''
})
class MockHeaderComponent {
}
Unfortunately, the following error occurred.
Chrome 93.0.4577.82 (Windows 10) SettingsPage should create FAILED
Failed: NG0300: Multiple components match node with tagname app-header. Find more at https://angular.io/errors/NG0300
error properties: Object({ code: '300' })
Error: NG0300: Multiple components match node with tagname app-header. Find more at https://angular.io/errors/NG0300
at throwMultipleComponentError (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:6779:1)
at findDirectiveDefMatches (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:10344:1)
at resolveDirectives (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:10158:1)
at elementStartFirstCreatePass (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:14772:1)
at ɵɵelementStart (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:14809:1)
at ɵɵelement (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:14888:1)
at SettingsPage_Template (ng:///SettingsPage.js:8:9)
at executeTemplate (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:9600:1)
at renderView (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:9404:1)
at renderComponent (node_modules/#angular/core/__ivy_ngcc__/fesm2015/core.js:10684:1)
Error: Expected undefined to be truthy.
at <Jasmine>
at UserContext.<anonymous> (src/app/components/settings/settings.page.spec.ts:24:23)
at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:364:1)
at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:292:1)
Chrome 93.0.4577.82 (Windows 10): Executed 26 of 26 (7 FAILED) (1.712 secs / 1.658 secs)
Can anyone tell me what I am doing wrong?
UPDATE 1:
My ComponentsModule class in which I integrate all reusable components:
import {NgModule} from '#angular/core';
import {HeaderComponent} from './header/header.component';
import { FooterComponent } from './footer/footer.component';
#NgModule({
declarations: [HeaderComponent, FooterComponent],
exports: [HeaderComponent, FooterComponent]
})
export class ComponentsModule{}
My html:
<ion-header>
<app-header [headline]="headlines.settings"></app-header>
</ion-header>
<ion-content>
</ion-content>
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { SettingsPageRoutingModule } from './settings-routing.module';
import { SettingsPage } from './settings.page';
import { ComponentsModule } from '../components.module';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ComponentsModule,
SettingsPageRoutingModule
],
declarations: [SettingsPage]
})
export class SettingsPageModule {}
setting.page.ts
import { Component, OnInit } from '#angular/core';
import { lablesHeadlines } from 'src/environments/lables';
#Component({
selector: 'app-settings',
templateUrl: './settings.page.html',
styleUrls: ['./settings.page.scss'],
})
export class SettingsPage implements OnInit {
lablesHeadlines = lablesHeadlines;
headlines = lablesHeadlines;
constructor() { }
ngOnInit() {
}
}
setting.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { SettingsPageRoutingModule } from './settings-routing.module';
import { SettingsPage } from './settings.page';
import { ComponentsModule } from '../components.module';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ComponentsModule,
SettingsPageRoutingModule
],
declarations: [SettingsPage]
})
export class SettingsPageModule {}
Problem Solved. https://testing-angular.com/testing-components-with-children/#testing-components-with-children showed me the solution. That I write unit tests, I can do with
schemas: [NO_ERRORS_SCHEMA] to ignore the components in the top-level components. The low-level components are ready checked in their own tests.
I strongly advise to use the link above if you want to learn about testing in Angular.
Here is my Updated Sourcecode:
import { HttpClientTestingModule } from '#angular/common/http/testing';
import { ComponentFixture, TestBed, waitForAsync } from '#angular/core/testing';
import { IonicModule } from '#ionic/angular';
import { AboutClientServiceService } from 'src/app/services/about-client-service.service';
import { AppComponent } from 'src/app/app.component';
import { MockAboutClientService } from 'src/app/Mock/MockAboutClientService';
import { AboutPage } from './about.page';
import { Component } from '#angular/core';
import { NO_ERRORS_SCHEMA } from '#angular/core';
describe('AboutPage', () => {
let component: AboutPage;
let fixture: ComponentFixture<AboutPage>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ AboutPage, MockHeaderComponent ],
schemas: [NO_ERRORS_SCHEMA],
imports: [IonicModule, HttpClientTestingModule],
providers: [AppComponent, AboutClientServiceService]
}).compileComponents();
TestBed.overrideComponent(
AboutPage,
{
set: {
providers: [
{ provide: AboutClientServiceService, useClass: MockAboutClientService }]
}
});
fixture = TestBed.createComponent(AboutPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', (done) => {
expect(component).toBeTruthy();
expect(component.version).toBeDefined();
done();
});
});
#Component({
selector: 'app-header',
template: ''
})
class MockHeaderComponent {
}
I am using angular in my ionic and I have followed everything based on this docs, so im using "#ionic/storage-angular", but my problem is when i refresh, data get deleted. Below is my code.
//app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
import { IonicStorageModule } from '#ionic/storage-angular';
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
IonicStorageModule.forRoot(),
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule
],
providers: [
{
provide: RouteReuseStrategy,
useClass: IonicRouteStrategy,
},
],
bootstrap: [AppComponent]
})
export class AppModule {}
//storage.service
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage-angular';
#Injectable({
providedIn: 'root'
})
export class StorageService {
private _storage: Storage | null = null;
constructor(private storage: Storage){
this.init();
}
async init() {
// https://github.com/ionic-team/ionic-storage
// If using, define drivers here: await this.storage.defineDriver(/*...*/);
const storage = await this.storage.create();
this._storage = storage;
}
public set(key: string, value: any) {
this._storage?.set(key, value);
}
public get(key){
return this._storage?.get(key);
}
public clear(){
this._storage.clear();
}
}
//this is how i used the service
await this.storageService.set('loginUser',{id: user.id,userName: user.first_name});
I'm trying to retrieve a request param from a deeplink to a Ionic 5 application using Deeplink plugin (authorization code provided by authorization server on successful authorization redirection).
Android intent filter seems correctly configured as the app is opening after successful authentication.
I keep having unmatched deeplinks with plugin_not_installed error.
app.module.ts:
import { HttpClientModule } from '#angular/common/http';
import { APP_INITIALIZER, NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { Deeplinks } from '#ionic-native/deeplinks/ngx';
import { SQLitePorter } from '#ionic-native/sqlite-porter/ngx';
import { SQLite } from '#ionic-native/sqlite/ngx';
import { Vibration } from '#ionic-native/vibration/ngx';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { IonicStorageModule } from '#ionic/storage';
import { ApiModule as NumeraApiModule } from '#lexi-clients/numera';
import { OidcUaaModule } from '#lexi/oidc-uaa';
import { AuthModule, OidcConfigService } from 'angular-auth-oidc-client';
import { environment } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SettingsService } from './settings/settings.service';
export function loadSettings(config: SettingsService) {
return () => config.load();
}
export function configureAuth(oidcConfigService: OidcConfigService) {
return () => oidcConfigService.withConfig(environment.authentication.angularAuthOidcClient);
}
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
AuthModule.forRoot(),
BrowserModule,
HttpClientModule,
IonicModule.forRoot(),
IonicStorageModule.forRoot(),
NumeraApiModule,
OidcUaaModule,
AppRoutingModule,
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: loadSettings,
deps: [SettingsService],
multi: true,
},
{
provide: APP_INITIALIZER,
useFactory: configureAuth,
deps: [OidcConfigService],
multi: true,
},
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
Deeplinks,
OidcConfigService,
SQLite,
SQLitePorter,
Vibration,
],
bootstrap: [AppComponent],
})
export class AppModule {}
app.component.ts:
import { AfterViewInit, Component, NgZone, OnDestroy, OnInit } from '#angular/core';
import { NavigationEnd, Router } from '#angular/router';
import { App, Plugins, StatusBarStyle } from '#capacitor/core';
import { AppCenterCrashes } from '#ionic-native/app-center-crashes';
import { Deeplinks } from '#ionic-native/deeplinks/ngx';
import { NavController, Platform } from '#ionic/angular';
import { LexiUser, UaaService } from '#lexi/oidc-uaa';
import { Observable, Subscription } from 'rxjs';
import { SettingsPage } from './settings/settings.page';
import { SettingsService } from './settings/settings.service';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent implements AfterViewInit, OnInit, OnDestroy {
constructor(
private platform: Platform,
private router: Router,
private idService: UaaService,
private settings: SettingsService,
private navController: NavController,
private deeplinks: Deeplinks,
private zone: NgZone
) {
this.platform.ready().then(async () => {
if (this.platform.is('mobile')) {
const { SplashScreen, StatusBar } = Plugins;
StatusBar.setStyle({ style: StatusBarStyle.Light });
SplashScreen.hide();
}
});
}
ngAfterViewInit() {
if (this.platform.is('mobile')) {
this.deeplinks.routeWithNavController(this.navController, { 'login-callback': SettingsPage }).subscribe(
(match) => {
console.log('Successfully matched route', match);
// Create our internal Router path by hand
const internalPath = '/settings';
// Run the navigation in the Angular zone
this.zone.run(() => {
this.router.navigateByUrl(internalPath);
});
},
(nomatch) => {
// nomatch.$link - the full link data
console.error("Got a deeplink that didn't match", nomatch);
}
);
}
}
}
I got it. My Ionic project is a module in an Angular multi-module project and plugin npm dependencies where added to root package.json.
Moving all Ionic-native related dependencies to package.json in Ionic project folder and running ionic cap sync again solved my problem.
Now the question is How to properly configure a Ionic module in an Angular mono-repo (aka multi-module project)?
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
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 { }