I've got a correct JWT token stored in local storage and an interceptor that I blatantly copied from a tutorial. However, it doesn't intercept and add headers to requests.
Here's where I make a request:
https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/information.service.ts
here's the interceptor:
https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/token.interceptor.ts
and my appmodule - I'm pretty sure it's correctly imported:
https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/app.module.ts
When I make a request I expect the interceptor to log messages that I specified to console and add the token to header, it doesn't do that though and I've got no idea why :/ I checked the code with some other tutorials found online and didn't see any differences capable of breaking my code. I also don't have enough experience with Angular to debug it properly.
Any help would be much apprecieated.
You are doing couple of things wrongly here:
Interceptors are used with HttpClientModule not with HttpModule. You are using HttpModule. You need to change to HttpClientModule
Add HttpClientModule in imports array in app.module.ts
Import HttpClient in your authentication.service.ts and take its reference in its constructor.
Refer below code:
//app.module.ts
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
.
.
.
#NgModule({
declarations: [
AppComponent,
.
.
.
],
imports: [
BrowserModule,
.
.
.,
HttpClientModule, //add here
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'add-information', component: AddInformationComponent },
{ path: '**', redirectTo: 'home' }
], { useHash: true })
],
providers: [
{ provide: 'BASE_URL', useValue: 'https://some URL/' },
UserService,
InformationService,
AuthenticationService,
AlertService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
and
//information.service.ts and authentication.service.ts
import { Injectable, Inject } from '#angular/core';
import { HttpClient} from '#angular/common/http'; //added import
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class InformationService {
constructor(private http: HttpClient, #Inject('BASE_URL') private baseUrl: string) { } //made changes in cunstructor
add(link: string, title: string, description: string) {
return this.http.post(this.baseUrl + 'api/Information', { link: link, title: title, description: description })
.map((response: Response) => {
console.log(response);
});
}
}
make similar changes in authentication.service.ts
Related
There are some similar discussions, but the solutions did not work. I've attempted to recreate the module a couple of times now and Angular still throws the error Maximum call stack size exceeded. The admin component is brand new as well. All of these have been generated using CLI.
Here's my code:
App Routing
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard } from './guards/auth/auth.guard';
const routes: Routes = [
{
path: 'dashboard',
pathMatch: 'full',
data: { authorized: [true] },
canActivate: [AuthGuard],
loadChildren: () =>
import('./modules/feature/dashboard/dashboard.module').then(
(m) => m.DashboardModule
),
},
///// this admin import is the issue and I know this because if I comment it out then the app works
///// fine...
{
path: 'admin',
pathMatch: 'full',
data: { authorized: [true] },
canActivate: [AuthGuard],
loadChildren: () =>
import('./modules/feature/admin/admin.module').then((m) => m.AdminModule),
},
{
path: '',
pathMatch: 'full',
data: { authorized: [false] },
loadChildren: () =>
import('./modules/feature/website/website.module').then(
(m) => m.WebsiteModule
),
},
// {
// path: '*',
// component: MainComponent,
// data: { authorized: [false] },
// },
];
#NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
exports: [RouterModule],
})
export class AppRoutingModule {}
Module
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { AdminRoutingModule } from 'src/app/routing/feature/admin-routing/admin-routing.module';
import { AdminComponent } from 'src/app/components/feature/admin/admin.component';
import { AdminService } from 'src/app/services/feature/admin.service';
#NgModule({
declarations: [AdminComponent],
imports: [CommonModule, AdminRoutingModule],
providers: [AdminService],
})
export class AdminModule {}
Admin Routing
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AdminComponent } from 'src/app/components/feature/admin/admin.component';
const routes: Routes = [
{
path: '',
component: AdminComponent,
children: [],
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class AdminRoutingModule {}
Sometimes you bang your head against the wall because you've looked over your code a hundred times. Knowing good and well that it's not an error on your end. To find that the error can be solved via something simple. Like stopping the server, closing visual studio....re-opening visual studio and re-booting the server.
Which btw, solved my issue.
I am creating an Angular application where I have implemented lazy loading. It is working fine but when ever I am making any HTTP request to the server the action is happening twice.
In my current structure I have created a shared module to store all the common modules and components. I am using ajax service to make all the api calls to backend, AuthTokenService is to store and handle Authentication token-
Feature Module -
import { NgModule, ModuleWithProviders } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule } from '#angular/router';
import { ReactiveFormsModule, FormsModule } from '#angular/forms';
//Importing HTTP Intercepter and services
import { HTTPInterceptorProvider } from '#/core/_HTTP-interceptor';
import { AjaxService, AuthTokenService } from '#/core/_services';
//Importing pipes
import { SummaryPipe } from '#/core/_pipes';
//Externel Plugins Modules
import { NgSelectModule } from '#ng-select/ng-select';
import { AnimatedNumbersComponent } from '#/modules/shared';
#NgModule({
declarations: [
AnimatedNumbersComponent,
//Pipes used are listed here
SummaryPipe
],
imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
RouterModule,
NgSelectModule
],
providers: [
],
exports: [
AnimatedNumbersComponent,
ReactiveFormsModule,
FormsModule,
NgSelectModule
]
})
export class FeatureModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [
AjaxService,
AuthTokenService,
HTTPInterceptorProvider
]
};
}
}
App Module -
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations'
import { FeatureModule } from './modules/featured/feature.module'
import { DatePipe } from '#angular/common';
import { NgxSpinnerModule } from "ngx-spinner";
import { AppComponent } from '#/app.component';
#NgModule({
declarations: [
AppComponent,
routingComponents
],
imports: [
HttpClientModule,
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
NgxSpinnerModule, // NGX Spinner
FeatureModule.forRoot()
],
providers: [
DatePipe
],
bootstrap: [AppComponent]
})
export class AppModule { }
App Routing Module -
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard, SecureOuterPagesGuard, SecureInnerPagesGuard } from "#/core/_guards";
// Home page of the application
import { IndexComponent } from '#/modules/index/index.component';
import {
LoginComponent,
RegisterComponent,
ForgetPasswordComponent,
ResetPasswordComponent
} from '#/modules/auth';
import {
PageNotFoundComponent,
InternalServerErrorComponent
} from '#/modules/shared';
const routes: Routes = [
{
path: '',
component: IndexComponent
},
{
path: 'login',
component: LoginComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'register',
component: RegisterComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'forget-password',
component: ForgetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'reset-password',
component: ResetPasswordComponent,
canActivate: [SecureOuterPagesGuard]
},
{
path: 'dashboard',
loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
canActivate: [AuthGuard]
},
{
path: 'internal-server-error',
component: InternalServerErrorComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class AppRoutingModule { }
export const routingComponents = [
IndexComponent,
LoginComponent,
RegisterComponent,
ForgetPasswordComponent,
ResetPasswordComponent,
SessionTimeOutComponent,
PageNotFoundComponent
]
Ajax Service -
import { Injectable } from '#angular/core';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpResponse } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map, timeout } from "rxjs/operators";
#Injectable()
export class AjaxService {
constructor(
private _http: HttpClient,
) { }
apiCall(
data: any,
url: any,
method: 'DELETE' | 'GET' | 'HEAD' | 'POST' | 'JSONP' | 'PUT',
isRawUrlFormat: boolean = false
){
// Checking if the provide url is in raw format or not
if (isRawUrlFormat == false) {
url = environment.API_URL + "/" + url;
}
// creating request variable of type Observable so that any component can subscribe it
let request: Observable<any>;
// setting methods of request type and passing params (url, data, headeers and observe to access complete response)
switch (method) {
case 'GET':
request = this._http.get(url, { observe: 'response' });
break;
case 'POST':
request = this._http.post(url, data, { observe: 'response' });
break;
case 'PUT':
request = this._http.put(url, data, { observe: 'response' });
break;
default:
request = this._http.request(method, url, { observe: 'response' });
}
// returning api result with status, if found any error returns that error
return request.pipe(
timeout(environment.AJAX_TIMEOUT),
map((apiResult : HttpResponse<any>) => {
const status : number = apiResult.status;
let responseObject = apiResult.body;
responseObject.status = status;
// if found status 202 means has a refreshtoken in response then again setting it in localstorage
if (status == 202) {
localStorage.setItem("userToken", apiResult.body.response.data.token);
}
return responseObject;
})
)
}
}
I started learning Angular 4 and got to the part with HTTP Client. Right now I'm trying to make an http call from the component (yes, I know I should transfer it to service, but still)
But for some reason, when I try to inject HttpClient into my Component I get the next error:
Uncaught Error: Can't resolve all parameters for PromocodeComponent:
(?).
Here's the code of my component:
import { Ticket } from '../../classes/Ticket.class'
import { Component, Input } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'promocode',
templateUrl: './promocode.template.html',
styleUrls: ['./promocode.styles.scss']
})
export class PromocodeComponent {
#Input() ticket: Ticket;
state: String = "normal";
promocode: String = "";
constructor(private http: HttpClient) {}
promocodeValidate(event): void{
console.log(this.promocode);
console.log(event);
this.http.get('/promocode/asdasda').subscribe(data => {
console.log(data);
});
}
}
And my app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { MovieBadgeComponent } from './movie-badge/movie-badge.component';
import { TicketComponent } from './ticket/ticket.component';
import { PromocodeComponent} from './promocode/promocode.component';
import { FormsModule } from '#angular/forms';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
MovieBadgeComponent,
TicketComponent,
PromocodeComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
It turned out, for me, that I forgot the #Injectable decorator on my service. In earlier angular (>=2), i remember the #Injectable as being optional... Guess not anymore?
Turns out, I missed
"emitDecoratorMetadata": true
in tsconfig
fml...
I got the same error when I ran unit testing (a spec.ts file) with Angular.
The following is what I did:
import { HttpClientModule, HttpClient } from '#angular/common/http';
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ],
imports: [
HttpClientModule
],
schemas: [NO_ERRORS_SCHEMA],
providers: [
HttpClient,
]
})
.compileComponents();
}));
and the error was gone.
The problem is when directly redirecting to
http://localhost:4200/about working fine but after pushing into
nginx server, when I try to redirect to www.webpage.com/about
getting error(nginx 404 error).
But its working fine when you redirect to www.webpage.com and then click on about.
Getting error only I am trying to open direct url as www.webpage.com/about or www.webpage.com/contact or
www.webpage.com/blog
import { NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { RouterModule } from "#angular/router";
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { appRoutes } from "./app-routing.module";
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { BlogComponent } from './blog/blog.component';
import { ClientsComponent } from './clients/clients.component';
import { ContactComponent } from './contact/contact.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
BlogComponent,
ClientsComponent,
ContactComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forRoot(appRoutes)
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule {
}
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { ClientsComponent } from './clients/clients.component';
import { ContactComponent } from './contact/contact.component';
import { BlogComponent } from './blog/blog.component';
export const appRoutes: Routes = [
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'clients', component: ClientsComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'page-not-found', component: PageNotFoundComponent },
{ path: '**', component: HomeComponent }
];
#NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {
}
You will need to configure your web server to redirect all unknown (404) requests to index.html, which will allow the Angular application to then route your user to the desired route/view.
You can try something like this :
error_page 404 =200 /index.html;
Source : How do I force redirect all 404's (or every page, whether invalid or not) to the homepage?
try_files $uri $uri/ /index.html;
This line has to be added in the nginx.conf incase of Windows server or in /etc/nginx/sites-enabled/default in case of ubuntu server.
That piece of code will look for angular paths before throwing a 404 error.
angular deployment check this out
I have a simple angular application and I am using Angular2 for the first time.
I am prompted with error in firefox console "EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: 'books/huckleberry'"
book.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-directory',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
book: string;
constructor(private route: ActivatedRoute) {
this.book= route.snapshot.params['book'];
}
ngOnInit() {
}
}
app.routes.ts
import { Routes, RouterModule } from "#angular/router";
import { BookComponent } from "./book/book.component";
import { HomeComponent } from "./home/home.component";
const APP_ROUTES: Routes = [
{
path:'book',
component: BookComponent,
children: [
{ path: 'book/:book', component: BookComponent}
]
},
{ path: '', component: HomeComponent }
];
export const APP_ROUTES_PROVIDER = RouterModule.forRoot(APP_ROUTES);
app.module.ts
...
import { BookComponent } from './book/book.component';
import { RouterModule } from "#angular/router";
#NgModule({
declarations: [
AppComponent,
BookComponent,
HomeComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'book', component: BookComponent },
// { path: '**', component: PageNotFoundComponent }
]),
RouterModule.forChild([
{
path: 'book', //parent path
children: [
{
path: 'book/:book',
component: BookComponent,
}
]
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
When i access http://localhost:4200/book, there is no error.
But when i access http://localhost:4200/book/huckleberry, using Angular2 for the first time.
I am prompted with error in firefox console "EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: 'book/huckleberry'"
Do you know how can i update app.module.ts?
I should be able to get {{book}} in book.component.html
I was able to solve this by the following codes below:
app.routes.ts
const APP_ROUTES: Routes = [
{ path:'directory', component: BookComponent },
{ path:'directory/:book', component: BookComponent },
{ path: '', component: HomeComponent }
];
app.module.ts
#NgModule({
declarations: [
AppComponent,
DirectoryComponent,
HomeComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'book', component: BookComponent },
{ path: 'book/:book', component: BookComponent }
// { path: '**', component: PageNotFoundComponent }
])
],
providers: [],
bootstrap: [AppComponent]
})
With the code above, i am now able to get the parameter and print it to the page via {{book}}