Angular 8 basic interceptor not called on page loading - javascript

I'm in the process of adding an interceptor to my angular 8 project. To make add bearer token. Unfortunately the interceptor does not seem to be called. My code:
I already:
Added HttpClientModule, HTTP_INTERCEPTORS and HttpConfigInterceptor imports in app.module.ts file.
Added HttpClientModule in imports section after BrowserModule.
Added { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true } in providers section.
app.module.ts file:
import { NgModule } from '#angular/core';
import { BrowserModule, Title } from '#angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { HttpConfigInterceptor } from './httpconfig.interceptor';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './home/home.component';
import { PrivacyPolicyComponent } from './privacy-policy/privacy-policy.component';
import { TermsOfUseComponent } from './terms-of-use/terms-of-use.component';
import { SnippetsComponent } from './snippets/snippets.component';
import { SnippetComponent } from './snippet/snippet.component';
import { NotFoundComponent } from './not-found/not-found.component';
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
PrivacyPolicyComponent,
TermsOfUseComponent,
SnippetsComponent,
SnippetComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [
Title,
{ provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
My interceptor file:
import { Injectable } from '#angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(request);
return next.handle(request);
}
}
I want just the console.log works.
Thks ^^.

Related

Component can't find imported element anymore when being shared

What I did so far:
I imported a component into the share module because I want to use it on 2 different Modules. Now when I'm recompiling the app it says that jodit-editor which is used by the shared component is not a known element. (worked completely normal before shared the component)
This is how the shared Component look like:
import { Component, forwardRef, Input, OnInit, ViewChild } from '#angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '#angular/forms';
import { JoditAngularComponent } from 'jodit-angular';
import { NGXLogger } from 'ngx-logger';
import { Widget } from 'src/app/models/widget';
import { IFile } from 'src/interfaces';
import { WysiwygTemplates } from './wysiwyg.templates';
import { FileService } from 'src/app/services/file.service';
import { StorageService } from 'src/app/services/storage.service';
#Component({
selector: 'app-wysiwyg',
templateUrl: './wysiwyg.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => WysiwygComponent),
}
],
})
This is how the share module look like:
import { CommonModule, registerLocaleData } from '#angular/common';
import { NgModule } from '#angular/core';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppButtonComponent } from 'src/app/utils/app-button/app-button.component';
import { ConfirmDialogComponent } from 'src/app/utils/confirm-dialog/confirm-dialog.component';
import { MatDialogModule } from '#angular/material/dialog';
import { FormErrorComponent } from 'src/app/utils/form-error/form-error.component';
import { HttpClient } from '#angular/common/http';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { TranslateModule, TranslateLoader, TranslateService } from '#ngx-translate/core';
import localeDe from '#angular/common/locales/de';
import { DragDropDirectiveModule } from './directives/filedrag-drop.directive';
import { DragDropModule } from '#angular/cdk/drag-drop';
import { WysiwygComponent } from 'src/app/utils/inputs/wysiwyg/wysiwyg.component';
registerLocaleData(localeDe);
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, '../i18n/', '.json');
}
#NgModule({
imports: [
DragDropDirectiveModule,
CommonModule,
MatDialogModule,
NgbModule,
TranslateModule.forChild({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
},
isolate: false
}),
],
declarations: [
WysiwygComponent,
AppButtonComponent,
ConfirmDialogComponent,
FormErrorComponent
],
exports: [
WysiwygComponent,
DragDropDirectiveModule,
AppButtonComponent,
ConfirmDialogComponent,
FormErrorComponent,
MatDialogModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
NgbModule,
TranslateModule,
DragDropModule
],
providers: [TranslateService]
})
export class SharedModule {}
When recompiling I getting this error:
The JoditAngularModule should be added to the imports of the shared module for your shared component to 'know' the element 'jodit-editor'.
This is the import statement.
import { JoditAngularModule } from 'jodit-angular';
Add it to the imports of shared module
imports:
[
// Other imports ,
JoditAngularModule
]
Hope this helps. Let me know if it works!

Angular9 'No provided for ActivatedRoute'

I'm beginner in Angular 9. I'm following an online video tutorial to excercise on angular, but my code (same of the tutorial) had a problem and I don't know of to figure out.
Actually, tutorial put routing stuffs all inside app.module.ts, but I use app-routing.module.ts to separate concerns.
When I launch 'ng serve --open', page still blank with the following error:
core.js:6185 ERROR NullInjectorError: R3InjectorError(AppModule)[ActivatedRoute -> ActivatedRoute -> ActivatedRoute]:
NullInjectorError: No provider for ActivatedRoute!
at NullInjector.get (http://localhost:4200/vendor.js:16926:27)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at R3Injector.get (http://localhost:4200/vendor.js:30642:33)
at NgModuleRef$1.get (http://localhost:4200/vendor.js:47971:33)
at Object.get (http://localhost:4200/vendor.js:45804:35)
at getOrCreateInjectable (http://localhost:4200/vendor.js:20704:39)
at Module.ɵɵdirectiveInject (http://localhost:4200/vendor.js:34541:12)
at NodeInjectorFactory.BookComponent_Factory [as factory] (http://localhost:4200/main.js:733:153)
at getNodeInjectable (http://localhost:4200/vendor.js:20849:44)
Actually I had this problem since I use providers. Is it hard to understand, because of console doesn't give any class line code. However I'm trying to describe here useful classes that should use it by following, if more classes needs, I will do that:
--app.module.ts--
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BookComponent } from './components/book/book.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { BooklistComponent } from './components/booklist/booklist.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
// for angular firebase #https://github.com/angular/angularfire/blob/master/docs/install-and-setup.md
import { AngularFireModule } from '#angular/fire';
import { AngularFirestore } from '#angular/fire/firestore';
import { environment } from '../environments/environment';
// import our service (that uses firebase)
import { CartService } from './services/cart/cart.service'
import { HttpModule } from '#angular/http';
#NgModule({
declarations: [
AppComponent,
BookComponent,
BooklistComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase), // have a look in firebase.ts
AngularFireModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
--app-routing.module.ts--
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { BookComponent } from './components/book/book.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { BooklistComponent } from './components/booklist/booklist.component';
const routes: Routes = [
{ path: 'books/:title', component: BookComponent},
{ path: 'books/:title/edit', component: BookEditComponent},
{ path: 'books', component: BooklistComponent},
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
--book.component.ts--
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import { BookModel } from '../../models/book/book.model';
import { CurrencyPipe } from '#angular/common';
import { ActivatedRoute } from '#Angular/router'
import { CartService } from '../../services/cart/cart.service';
#Component({
selector: 'book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
#Input() book: BookModel;
#Output() addToCart: EventEmitter<BookModel> = new EventEmitter();
constructor(private route: ActivatedRoute, private cs: CartService) {
route.params.subscribe(res => {
this.book = BookModel.find(res['title']);
});
}
ngOnInit(): void {
}
sendToCart() {
this.addToCart.emit(this.book);
// the following method is added in cart.service.ts
this.cs.add(this.book);
}
// methods
votesCounter() {
return this.book.upvotes;
}
upvote() {
return this.book.upvotes++;
}
}
As I use app-routing.module.ts, there is a quite difference in app.module of tutorial (that puts also routing stuffs inside it):
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestore } from 'angularfire2/firestore';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
import { BookComponent } from './components/book/book.component';
import { BookListComponent } from './components/book-list/book-list.component';
import { BookEditComponent } from './components/book-edit/book-edit.component';
import { TreeComponent } from './components/tree/tree.component';
import { NgInitDirective } from './directive/ng-init/ng-init.directive';
import { CartService } from './services/cart/cart.service';
const bookRoutes: Routes = [
{ path: 'books/:title', component: BookComponent },
{ path: 'books/:title/edit', component: BookEditComponent },
{ path: 'books', component: BookListComponent },
{
path: '',
redirectTo: 'books/',
pathMatch: 'full'
}
]
#NgModule({
declarations: [
AppComponent,
BookComponent,
BookListComponent,
BookEditComponent,
TreeComponent,
NgInitDirective
],
imports: [
RouterModule.forRoot(bookRoutes),
BrowserModule,
FormsModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I tryed with solutions given from similar questions, but it doesn't work.
You have a typing error,
change #Angular/router with #angular/router in book.component.ts

Browsermodule error for NgxDatetimeRangePickerModule

Hi my application was working fine till i added NgxDatetimeRangePickerModule, Once i added it in my shared module , I am getting BrowserModule has already been loaded error. Borwser module is present in only app.module and not in any module. What might be the issue.
Error :
vendor.js:77185 ERROR Error: Uncaught (in promise): Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.
Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.
App.module.ts
import { NgModule, ApplicationModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { NgHttpLoaderModule } from 'ng-http-loader';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
// 3rd party module
import { NgxDatetimeRangePickerModule } from 'ngx-datetime-range-picker';
// import { Cardscomponent } from './cards/cards.component';
import { NotificationToastComponent } from './_shared/notification-toast/notification-toast.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './_services/auth.guard';
import { AuthInterceptor } from './_services/auth.interceptor';
import { ErrorInterceptor } from './_services/error.interceptor';
import { SharedModule } from './_shared/shared.module';
#NgModule({
declarations: [
AppComponent,
NotificationToastComponent,
LoginComponent,
],
imports: [
SharedModule,
BrowserModule,
BrowserAnimationsModule,
ApplicationModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
HttpClientModule,
NgHttpLoaderModule.forRoot(),
NgbModule,
],
providers: [
AuthGuard,
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
],
entryComponents: [
NotificationToastComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
My Shared Module:
import { NgModule } from '#angular/core';
import { FilterDataPipe } from '../_pipes/filter-data.pipe';
import { AngularMaterialModule } from '../angular-material.module';
import { CommonModule } from '#angular/common';
import { AngularKendoModule } from '../angular-kendo.module';
import { NgxDatetimeRangePickerModule } from 'ngx-datetime-range-picker';
import { MustMatchDirective } from '../_helpers/must-match.directive';
#NgModule({
imports:[
CommonModule,
AngularMaterialModule,
AngularKendoModule,
],
declarations: [
FilterDataPipe,
MustMatchDirective
],
exports: [
CommonModule,
FilterDataPipe,
AngularMaterialModule,
MustMatchDirective,AngularKendoModule,
NgxDatetimeRangePickerModule
]
})
export class SharedModule {}
My child Module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { Cardscomponent } from './cards.component';
import { SharedModule } from '../_shared/shared.module';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { CardsRoutingModule } from './cards-routing.module';
import { CardDetailsComponent } from './card-details/card-details.component';
import { NgMultiSelectDropDownModule } from 'ng-multiselect-dropdown';
#NgModule({
imports: [
CommonModule,
SharedModule,
FormsModule,
ReactiveFormsModule,
CardsRoutingModule,
NgbModule,
NgMultiSelectDropDownModule.forRoot(),
],
declarations: [Cardscomponent,CardDetailsComponent]
})
export class CardsModule { }
Remove NgxDatetimeRangePickerModule from app.module move it to shared module.
In shared.module import NgxDatetimeRangePickerModule.forRoot() inside import section.
Thanks
Rahul Tokase

Angular auth.guard no persisten auth

Authentication doesn't seem to persist after page has been refreshed. Whenever I login, it successfully redirects me. but, when i refreshed, accessing is not possible anymore.
here is the auth guard
router
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './components/nav/nav.component';
import { HomeComponent } from './components/home/home.component';
import { GalleryComponent } from './components/gallery/gallery.component';
import { FooterComponent } from './components/footer/footer.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { FIREBASECONFIG as firebaseConfig } from './config/firebase-config';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { ScrollToModule } from 'ng2-scroll-to';
import { NgxCarouselModule } from 'ngx-carousel';
import { AnimateOnScrollModule } from 'ng2-animate-on-scroll';
import { AuthService } from './services/auth.service';
import { AuthGuard } from './services/auth.guard.service';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'gallery', component: GalleryComponent, canActivate: [AuthGuard] }
];
#NgModule({
declarations: [
AppComponent,
NavComponent,
HomeComponent,
GalleryComponent,
FooterComponent,
],
imports: [
FormsModule,
BrowserModule,
AppRoutingModule,
NgxCarouselModule,
NgbModule.forRoot(),
ScrollToModule.forRoot(),
RouterModule.forRoot(routes),
AnimateOnScrollModule.forRoot(),
HttpClientModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireAuthModule,
AngularFireDatabaseModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
exports: [
TranslateModule
],
providers: [AngularFireDatabase, AuthService, AuthGuard],
bootstrap: [AppComponent]
})
auth.guard.ts
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { AngularFireAuth } from 'angularfire2/auth';
import { Injectable, OnInit } from '#angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '#angular/router';
#Injectable()
export class AuthGuard implements CanActivate {
public user = null;
constructor(private fireauth: AngularFireAuth, private router: Router) {
this.fireauth.auth.onAuthStateChanged((user) => {
if (user) {
this.user = this.fireauth.auth.currentUser;
}
});
}
ongOnInit() {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
if (this.user) {
return true;
} else {
this.router.navigate(['']);
return false;
}
}
}
the routes are ok according to me, i thing that the problem most be on the auth guard, i guess.
Try this code
constructor(
private router:Router,
public fireauth:AngularFireAuth
){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
return this.fireauth.authState.map((auth) => {
if(auth == null) {
this.router.navigate(['/']);
return false;
} else {
return true;
}
});
}
i think this.fireauth.auth.onAuthStateChanged is used in older versions

Angular 4.3.3 : Why can't I get a DI in the Service

Before I ask, I do not speak English very well.
first, I'm #angular#4.3.3 and my typescript version is ~2.3.3
Ask.
I lazy loaded the LoginModule
AppRoute
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login#LoginModule' }
];
export const AppRoutes = RouterModule.forRoot(routes);
and my
AppModule
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { AppRoutes } from './routing/app.routing';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutes,
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
and
LoginModule
import { CommonModule } from '#angular/common';
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { ErrorCodeService } from '../shared/service/error-code/error-code.service';
import { LoginService } from '../shared/service/login/login.service';
import { LoginComponent } from './login.component';
#NgModule({
imports: [
HttpClientModule,
CommonModule,
FormsModule,
RouterModule.forChild([
{ path: '', component: LoginComponent }
])
],
exports: [],
declarations: [ LoginComponent ],
providers: [
ErrorCodeService,
LoginService,
],
})
export class LoginModule { }
and
LoginService
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorCodeService } from '../error-code/error-code.service';
import { RequestCore } from '../request-core';
#Injectable()
export class LoginService extends RequestCore {
constructor(
protected http: HttpClient,
private errorCode: ErrorCodeService,
) {
super(http, '/Login');
}
public load(userid: string, passwd: string): Observable<any> {
const params = new HttpParams()
.append('id', userid)
.append('passwd', passwd);
return this.get({ params })
.map(res => {
if (res.islogin === 'true') {
return res.sendRedirect;
}
throw new Error(this.errorCode.getErrorMsg(res.reason));
});
}
}
RequestCore
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import { HttpOptions } from '../models';
export abstract class RequestCore {
constructor(
protected http: HttpClient,
private url: string,
) {
// 개발 모드에서는 proxy를 위해 url에 /dev 접두어를 붙인다.
if (environment.production === false) {
url = '/dev' + url;
}
}
protected get(options?: HttpOptions): Observable<any> {
return this.http.get(this.url, options);
}
protected post(options?: HttpOptions): Observable<any> {
return this.http.post(this.url, {}, options);
}
}
This is my error
I don't know why I can't DI in LoginService
ReuquestCore Are you making the wrong inheritance?
Teach me
Thank you!
Re:
An error occurs when the first screen is loaded.
When the next hmr is updated, no error occurs.

Categories

Resources