No Provider for AuthHttp! Angular2-Jwt provider issue - jwt

At least I thought I was providing correctly. Below are the relevant snippets of my app.module file and the service in which I use AuthHttp. I followed the configuration in the ReadMe for creating the factory method to provide for AuthHttp, but there is a persisting issue with it not being recognized in my service. I've read the literature on nested dependency injections, and I feel as though I'm doing things correctly.
app.module.ts
import { Http, RequestOptions } from '#angular/http';
import { provideAuth, AuthHttp, AuthConfig } from 'angular2-jwt/angular2-jwt';
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig(), http, options);
}
#NgModule({
declarations: [
AppComponent,
ButtonFormComponent,
...
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule,
AppRoutingModule
],
providers: [
{
provide: LocationStrategy,
useClass: HashLocationStrategy
},
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
},
employee.service.ts
import { AuthHttp } from 'angular2-jwt/angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { ApiSettings } from './api-settings';
#Injectable()
export class EmployeeService {
api: String;
auth: String;
constructor(private http: Http, private authHttp: AuthHttp) {
this.api = ApiSettings.API;
this.auth = ApiSettings.Auth;
}

You can get rid of this issue by just using following import in your app.module.ts, here the key import for you is, AUTH_PROVIDERS.
Also, make sure you include AUTH_PROVIDERS in the providers array.
import { AuthHttp, AUTH_PROVIDERS, provideAuth, AuthConfig } from
'angular2-jwt/angular2-jwt';
#NgModule({
providers: [AUTH_PROVIDERS]
})

Related

Validation a accessToken in NESTJS

Im having some issues with validation a jwt in nestjs. Alot of documentation and tutorials show how to create token etc. I just want to validate it and protect graphql resolvers.
In my jwt.strategy.ts i have this code:
import { Injectable } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import { PassportStrategy } from '#nestjs/passport';
import { passportJwtSecret } from 'jwks-rsa';
import { ExtractJwt, Strategy } from 'passport-jwt';
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
secretOrKeyProvider: passportJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: 'xxxxx',
}),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
audience: 'urn:microsoft:userinfo',
issuer: 'xxxxx',
algorithms: ['RS256'],
});
}
validate(payload: unknown): unknown {
return payload;
}
}
And in my authz module i have:
import { Module } from '#nestjs/common';
import { PassportModule } from '#nestjs/passport';
import { JwtStrategy } from './jwt.strategy';
#Module({
imports: [PassportModule.register({ defaultStrategy: 'jwt' })],
providers: [JwtStrategy],
exports: [PassportModule],
})
export class AuthzModule {}
In my resolvers i use the UseGuards decorator:
#UseGuards(AuthGuard('jwt'))
All this should work, but i get an error:
TypeError: Cannot read properties of undefined (reading 'logIn')
I dont want to do any login, just validate the token.
ANy tips on this? Have tried google, been at it for hours. Thanks!

Nestjs with Mongodb native driver problem with injecting the connection

I've used Mongodb native node driver for my Nestjs project and when I run nest run command I faced this error:
Nest can't resolve dependencies of the ProjectService (?). Please make
sure that the argument DATABASE_CONNECTION at index [0] is available
in the AppModule context.
Potential solutions:
If DATABASE_CONNECTION is a provider, is it part of the current AppModule?
If DATABASE_CONNECTION is exported from a separate #Module, is that module imported within AppModule? #Module({
imports: [ /* the Module containing DATABASE_CONNECTION */ ] })
The provider for DATABASE_CONNECTION has been defined in the database module and database module has been imported in the appModule and I can't find out the problem.
src/app.module.ts
import { Module } from '#nestjs/common';
import { AppController } from './app.controller';
import { ProjectController } from './project/project.controller';
import { ProjectService } from './project/project.service';
import { DatabaseModule } from './database.module';
#Module({
imports: [DatabaseModule],
controllers: [AppController, ProjectController],
providers: [ProjectService],
})
export class AppModule {}
src/database.module.ts
import { Module } from '#nestjs/common';
import { MongoClient, Db } from 'mongodb';
#Module({
providers: [{
provide: 'DATABASE_CONNECTION',
useFactory: async (): Promise<Db> => {
try {
const client = await MongoClient.connect('mongodb://127.0.0.1:27017', {
useUnifiedTopology: true
});
return client.db('app-test');
} catch(e){
throw e;
}
}
}
],
exports:[
'DATABASE_CONNECTION'
]
})
export class DatabaseModule { }
src/project/project.service.ts
import { Inject, Injectable } from '#nestjs/common';
import { Db } from 'mongodb';
import { Project } from '../models/project.model';
#Injectable()
export class ProjectService {
constructor(
#Inject('DATABASE_CONNECTION')
private db: Db
) {
}
async getProjects(): Promise<Project[]> {
return this.db.collection('Projects').find().toArray();
}
}
I finally fixed the error. I removed the content of dist folder and built the project again and start it and error fixed!
I think this could be helpful https://stackoverflow.com/a/66771530/3141993 for avoiding these type of errors without removing the content of dist file manually.

How to lazy load modals in ionic4

I need some help with lazy loading of modals in ionic 4. I googled a lot but can't find an exact solution.
I have several modals on a page. And I want to lazy load them. Following is the example of two modals on a page
In one of my modal, I need AndroidPermissions, so I have to import it in the module file of the page because importing in the module file of the modal is not working.
Why this is happening? Can ionic modals not be lazy-loaded?
Thank you in advance
home.module.ts
import { AddressPage } from '../pages/address/address.page'; // modal 1
import { AddAddressPage } from '../pages/add-address/add-address.page' // modal 2
import { AndroidPermissions } from '#ionic-native/android-permissions/ngx';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild([
{
path: '',
component: HomePage
}
])
],
declarations: [HomePage, AddressPage, AddAddressPage],
entryComponents :[AddressPage , AddAddressPage],
providers :[AndroidPermissions]
})
export class HomePageModule {}
To lazy loading of modals follow following steps
Add modal page's module in the import of your page
Remove all routing of modal as we don't need it
Remove modal's entry from app.routing.module
Add modal page in entryComponents of modal's module
In my case, I had two modals. The second modal is opened inside the first modal.
So I have to add modale1module in the import of the page and modal2module in the import of modal1module
base page.module
import { AddressModalPageModule } from '../address-modal/address-modal.module';
const routes: Routes = [
{
path: '',
component: CartsPage
}
];
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes),
ReactiveFormsModule,
AddressModalPageModule
],
declarations: [CartsPage ],
})
export class CartsPageModule {}
modal1.module
import { AddressModalPage } from './address-modal.page';
import { AddAddressModalPageModule } from '../add-address-modal/add-address-modal.module';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
AddAddressModalPageModule
],
declarations: [AddressModalPage],
entryComponents:[AddressModalPage]
})
export class AddressModalPageModule {}
modal2.module
import { AddAddressModalPage } from './add-address-modal.page';
import { AndroidPermissions } from '#ionic-native/android-permissions/ngx';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ReactiveFormsModule
],
declarations: [AddAddressModalPage],
entryComponents:[AddAddressModalPage],
providers :[
AndroidPermissions, ]
})
export class AddAddressModalPageModule {}
Ionic 4 supports lazy loading for modals, but as the documentation says with nuance:
it's important to note that the modal will not be loaded when it is opened, but rather when the module that imports the modal's module is loaded
To lazy load a modal you need to:
import your modal page module into the module of a component from which
the modal page will be opened
ensure you added the modal page into entry components list of the modal page module
You should be able to access your singleton provider inside your modal, by just importing it into the modal's page (Angular 8)
for example your modal's module ts looks like this:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
// import the component for your modal's content:
import { MyModalComponent } from '../my-modal/my-modal.component'
#NgModule({
// add it to entry components and to the declarations:
entryComponents: [MyModalComponent],
declarations: [MyModalComponent],
imports: [
CommonModule
]
})
export class LazyLoadedModalModule { }
Then importing it into the module of the page that will call the modal would look like this:
...
// import lazy loaded module:
import { LazyLoadedModalModule } from '../lazy-loaded-modal/lazy-loaded-modal.module';
#NgModule({
imports: [
IonicModule,
CommonModule,
// add it to the imports:
LazyLoadedModalModule,
RouterModule.forChild([{ path: '', component: Tab1Page }])
],
declarations: [Tab1Page]
})
export class Tab1PageModule {}
now in the page where you need to create the modal you need to import the component and use modal controller:
import { Component } from '#angular/core';
import { ModalController } from '#ionic/angular';
import { MyModalComponent } from '../my-modal/my-modal.component'
#Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
constructor(private modalCtrl: ModalController) {}
async openModal() {
const modal = await this.modalCtrl.create({
component: MyModalComponent
});
await modal.present();
}
}

Custom ngx-translate loader, receiving cannot set property 'http' of undefined

I'm setting up a Ionic 4 project using ngx-translate and a custom loader to load JSON translations from an external domain. I've been following this guys take on it: https://forum.ionicframework.com/t/ngx-translate-translatehttploader-with-external-url/99331/4
Stackblitz link: https://stackblitz.com/edit/ionic-v4-jdfbh6
So this is my custom loader (provider).
#Injectable()
export class TranslationProvider implements TranslateLoader {
constructor(private http: HttpClient) {
console.log('Hello TranslationProvider Provider');
}
getTranslation(lang: string): Observable<any> {
return Observable.create(observer => {
this.http.get<any>(Environment.base_api + '/static/translations/' + lang + 'json', {
headers: {'Content-Type': 'application/json'}}).subscribe((res: Response) => {
observer.next(res.json());
observer.complete();
});
});
}
}
and in my app.module.ts (imports):
imports: [
BrowserModule,
IonicModule.forRoot(App),
IonicStorageModule.forRoot(),
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (TranslationProvider),
deps: [HttpClient]
}
})
],
The error message I receive is:
TypeError: Cannot set property 'http' of undefined at TranslationProvider (http://localhost:8100/build/main.js:1073:19)
I made a working sample app, here's the gist:
https://gist.github.com/olivercodes/a34be66e5b69edcd96038e5a4518b16e
You need to change #Injectable() to
#Injectable({
providedIn: 'root'
})
Also, make sure these are your import locations:
// In the service file
import { HttpClient } from '#angular/common/http';
import { TranslateLoader } from '#ngx-translate/core'
// in app.module
import { TranslateLoader } from '#ngx-translate/core'
import { HttpClient, HttpClientModule } from '#angular/common/http';
Use my provided gist and make sure your imports are right.

Sending Authorization Header in Ionic 3 and Angular 5 through HTTPClient

I am calling REST API from ionic 3 and Http Client, I am using Http Interceptor, When I am setting header name in the code, it is going under "Access-Control-Request-Headers:" see the attached Screenshot
and my code is :
import { Injectable, NgModule } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '#angular/common/http';
import { HTTP_INTERCEPTORS } from '#angular/common/http';
#Injectable()
export class HttpsRequestInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const dupReq = req.clone({ headers: req.headers.set('Access-Control-Allow-Origin', '*').append('ABC','xxx') });
return next.handle(dupReq);
}
};
#NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpsRequestInterceptor, multi: true }
]
})
export class InterceptorModule { }
You have handled cors on the frontend, But it also needs to be handled from the backend, Moreover, install this extension and turn it on before making the http call and you will be able to receive response
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en