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

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.

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!

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(RegisterPageModule)[AccessProviders -> AccessProviders]

I have a problem in my Ionic app with AngularJS, in register.page.ts; when i am going to add the AccessProviders path in the project the project says:ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(RegisterPageModule)[AccessProviders -> AccessProviders -> AccessProviders -> AccessProviders]: NullInjectorError: No provider for AccessProviders!
I have created the access providers folder and files manually.
register.page.ts
import {Router} from "#angular/router";
import { ToastController, LoadingController, AlertController } from "#ionic/angular";
import {AccessProviders} from "../../providers/access-providers";
#Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
name: string = "";
gender: string = "";
dob: string = "";
email: string = "";
password: string = "";
confirm_password: string = "";
disabledButton;
constructor(
private router: Router,
private toastCtrl: ToastController,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController,
private accsPrvds: AccessProviders,
) { }
ionViewDidEnter() {
this.disabledButton = false;
}
access-providers.ts
import { HttpClient, HttpHeaders, HttpErrorResponse } from "#angular/common/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
#Injectable()
export class AccessProviders {
server: string = 'http://localhost:8100/register'; //should change.
constructor(
public http: HttpClient
) {
}
postData(body, file) {
let headers = new HttpHeaders({
'Content-Type': 'application/json; charset=UTF-8'
});
let options = {
headers: headers
};
return this.http.post(this.server + file, JSON.stringify(body), options)
.timeout(59000)// 59 sec timeout
.map(res => res);
}
}
How i can solve this problem? I hope got my answer.
ADD blow code inside your access-providers.ts file:
import { Injectable } from '#angular/core'; // at top
#Injectable({
providedIn: 'root' // just before your class
})
export class AccessProviders {}
Make sure that HttpClientModule is registered at the level of AppModule
Just add this in your app.module.ts
import { HttpClientModule } from '#angular/common/http'
/////
#NgModule({
imports: [ HttpClientModule ]
})
It looks like you need to add it under providers in your app.modules.ts file.
If you only need the class in one page you could add it to the page.module.ts file of the corresponding page.
I had a similar problem, I found my solution here:
https://github.com/angular/angular/issues/20339#issuecomment-354767429
I had to import
"import {HttpClientModule} from '# angular / common / http';" in
imports: [HttpClientModule], inside the module that references the component.
In your app module
You have to add at the top :
import {AccessProviders} from "../../providers/access-providers";
On the same file, find providers and just add AccessProviders to the list of providers.

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

Disable headers on particular request HttpClient angular 5?

I have upgraded my app from ng4 to ng5 v-5.2.9. I have set the headers for every request. But on my app some request does not support headers, so how to disable headers from particular request not every request.
Previously with ng4 I was using http but now facing issues as its not supported any more in ng5
setHeader.ts
import { Injectable } from '#angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
#Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`,
Ip:currentUser.Ip
}
});
}
return next.handle(request);
}
}
app.module.ts:-
import { HTTP_INTERCEPTORS } from '#angular/common/http';
#NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AddHeaderInterceptor,
multi: true,
}],
})
export class AppModule {}
Basically headers are used for token and for autorization nut some of the API doesn't need to be authorized and hence headers are not required, by using setHeader it applies to all api calls. I have got HttpErrorResponse on my browser console. where its not required
Thanks!

No Provider for AuthHttp! Angular2-Jwt provider issue

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]
})