I had already know we could create global interceptors from this code below:
import { Module } from '#nestjs/common';
import { APP_INTERCEPTOR } from '#nestjs/core';
#Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor,
},
],
})
export class AppModule {}
Source: documentation
However, what if I want to have let say, UserInterceptor.
UserInterceptor will get user from database and transform the request.
UserInterceptor need to inject let say UserService.
And I want to use UserInterceptor globally.
#Injectable()
export class UserInterceptor {
constructor(private readonly service: UserService) {}
}
From documentation, we can't do app.useGlobalInterceptors(new UserInterceptor()) because UserInterceptor need 1 argument in the constructor (UserService).
And since we had use APP_INTERCEPTOR for LoggingInterceptor, I didn't found another way to assign another value to APP_INTERCEPTOR to use the interceptor globally.
For example I think the problem will solved if we could do:
providers: [
{
provide: APP_INTERCEPTOR,
useClass: [LoggingInterceptor, UserInterceptor]
}
]
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor
},
{
provide: APP_INTERCEPTOR,
useClass: UserInterceptor
}
]
Just like this
Related
Considering the image, I have a component (1) + module (2) + routing (3)(in "app-routing.module.ts"). To avoid too much code in "app-routing.module.ts", I want to move the routing code (3) in other file (suppose "product.routes.ts"). How can I do this considering I'm using Angular 2? Thanks!
This would be the AppComponentRoutingModule which I use, which can be extended with further files, usually that is one routes file per nested routing (to be imported in the corresponding module). The components and routes may vary, but it generally works alike this (guards skipped for the sake of brevity):
Create src/app/routes/app.routes.ts with content alike:
import { Routes } from '#angular/router';
import { ErrorPage } from 'src/app/pages/error/error.page';
export const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' }, // main entry point.
{ path: 'home', loadChildren: () => import('src/app/pages/home/home.module').then(m => m.HomeModule) },
{ path: 'error/:id', component: ErrorPage, pathMatch: 'full' },
{ path: '**', redirectTo: '/error/404' }
];
The nested routes don't look much different, for example src/app/routes/home.routes.ts:
export const homeRoutes: Routes = [{
path: '',
component: HomePage,
children: [
...
]
}];
Create src/app/app.component.routing.module.ts with content alike:
import { NgModule } from '#angular/core';
import { PreloadAllModules, RouterModule } from '#angular/router';
import { appRoutes } from './routes/app.routes';
#NgModule({
imports: [
RouterModule.forRoot(appRoutes,{preloadingStrategy: PreloadAllModules})
],
exports: [ RouterModule ]
})
export class AppComponentRoutingModule {}
Then import AppComponentRoutingModule in app.module.ts:
import { RouterModule } from '#angular/router';
import { AppComponent } from 'src/app/app.component';
import { AppComponentRoutingModule } from 'src/app/app.component.routing.module';
...
#NgModule({
declarations: [ AppComponent ],
imports: [
RouterModule,
AppComponentRoutingModule,
...
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
In order to enable verbose logging, enableTracing: true is your friend.
I'm trying to do authentication with AngularFire. During ng serve, any attempt to instantiate an auth provider (such as firebase.auth.GoogleAuthProvider) results in a crash. I'm doing the exact same thing as the AngularFireAuth quickstart example. Am I missing something?
My app is quite minimal:
// app.component.ts
import { Component } from "#angular/core";
import { AngularFireAuth } from '#angular/fire/auth';
import { auth } from 'firebase/app';
#Component({...})
export class AppComponent {
constructor(private afAuth: AngularFireAuth) { }
ngOnInit() {
this.afAuth.signInWithRedirect(new auth.GoogleAuthProvider());
}
}
// app.module.ts
import { AngularFireModule } from "#angular/fire";
import { AngularFireAuthModule } from '#angular/fire/auth';
...
#NgModule({
declarations: [AppComponent],
imports: [
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// package.json
"dependencies": {
"#angular/core": "~9.1.4",
"#angular/fire": "^6.0.0-rc.2",
"firebase": "7.14.3",
...
},
I have found this question with a similar problem, but they're not using AngularFire, just plain Firebase. With AngularFire I don't think I'm supposed to manually include the Firebase scripts in my index.html.
I've found the real solution. "angular-auth-firebase" must be passed to initializeApp() when importing the AngularFire module in the app module:
#NgModule({
declarations: [ ... ],
imports: [
AngularFireModule.initializeApp(environment.firebase, "angular-auth-firebase"),
AngularFireAuthModule,
...
],
...
})
export class AppModule { }
Old answer (workaround):
I have found a workaround here. If I simply add import "firebase/auth"; to app.module.ts, everything works, though I'm not sure this should be the permanent fix.
Here i'm using angular2 Here i Register EditEmployeeByIdComponent in EmployeeModule when user Click on that URL its shoud Redirect me to that Componet
EditEmployeeByIdComponent
import { Component } from "#angular/core"
#Component({
templateUrl:'../../ui/employee/EditEmployee.html'
})
export class EditEmployeeByIdComponent {
}
I Registerd EditEmployeeByIdComponent in EmployeeModule
#NgModule({
imports: [RouterModule.forChild(EmployeeRoute), FormsModule, CommonModule, HttpModule],
declarations: [EmployeeComponent, EditEmployeeByIdComponent],
bootstrap: [EmployeeComponent],
providers: [EmployeeService]
})
export class EmployeeModule {
}
From this Im calling
<tr *ngFor="let emp of employee">
<a (click)="GetById(emp.Emp_Id)"> {{emp.EmpName}} </a>
</tr>
GetById(Id:number) {
this._router.navigate(['../editemployeebyidcomponent'], {})
}
you have to provide router outlet in you parent component so allow angular to render child on it so in your example you have to declare a parent component lets say Employee.component.ts and it's equivalent template Employee.component.html and inside .html write that directive don't forget to declare this parent inside your EmployeeModule
const employeeRoutes: Routes = [
{path : 'employee', component: EmployeeComponent,children: [
{path : 'editemployeebyidcomponent', component: EditEmployeeByIdComponent},
];
#NgModule({
imports: [
CommonModule,
RouterModule.forChild(employeeRoutes)
],
declarations: [
EmployeeComponent,EditEmployeeByIdComponent
],
exports :[RouterModule]
})
export class EmployeeModule { }
employee.component.html
<router-outlet></router-outlet>
app.module.ts
const appRouts: Routes = [
{path: 'employee' , component: EmployeeComponent}
];
#NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(appRouts),
],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
your navigation route inside parent component should be like that
GetById(Id:number) {
this._router.navigate(['../editemployeebyidcomponent'],{relativeTo: this.currentActivatedRoute})
}
Either you make the route absolute
GetById(Id:number) {
this._router.navigate(['/editemployeebyidcomponent'])
}
I'm usung Angular 2 Universal:
I have a service:
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { Page } from './page';
#Injectable()
export class MyService {
constructor(private http: Http) { }
getPage(id: number): Observable<Page> {
return null;
}
}
Unit test:
import { TestBed, async, inject } from '#angular/core/testing';
import { PageService } from './workflow.service';
describe('Service: Workflow', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [WorkflowService]
});
});
it('should ...', inject([PageService], (service: PageService) => {
expect(service).toBeTruthy();
}));
});
My app module:
#NgModule({
bootstrap: [AppComponent],
declarations: [
AppComponent,
HomeComponent,
WorkflowComponent
],
imports: [
HttpModule,
UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'workflow/:id', component: WorkflowComponent }
])
]
})
export class AppModule {
}
When I run unit test I get: Error: No provider for Http!
UniversalModule in app.module should import http module already as indicated in the comments.
I'm using the latest Angular universal.
Should I add http in the test?
This article gave me an idea how to fix it:
http://chariotsolutions.com/blog/post/testing-angular-2-0-x-services-http-jasmine-karma/
This is a follow up to Angular 2.0 router not working on reloading the browser
Even if I configure the router to use the HashLocationStrategy I still get the url paths without #. I follow exactly the Angular2 docs https://angular.io/docs/ts/latest/tutorial/toh-pt5.html
and set the location strategy as described here https://angular.io/docs/ts/latest/guide/router.html
My bootstrap:
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {
ROUTER_PROVIDERS,
LocationStrategy,
HashLocationStrategy
} from 'angular2/router';
import {AppComponent} from './app.component';
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy })
]);
And the router config:
#RouteConfig([
{
path: '/detail/:id',
name: 'HeroDetail',
component: HeroDetailComponent
},
{
path: '/heroes',
name: 'Heroes',
component: HeroesComponent
},
{
path: '/dashboard',
name: 'Dashboard',
component: DashboardComponent,
useAsDefault: true
}
])
I'd expect to see a url like http://localhost/#/dashboard in the browser, but I get http://localhost/dashboard.
What am I missing?
Try to move the ROUTER_PROVIDER and provide(..)-stuff into your app.component.ts file.
In there you should paste it into the #Component.providers-Array.
For a more detailed answer have a look at this post, it solved my problem which seems to be close to yours:
https://stackoverflow.com/a/35879541/4977476
My understanding (which might be wrong, I am just beginning with Angular2) is that the useAsDefault acts as a redirect. But this isn't needed when using hash locations, since from the server's point of view, all pages are on '/' anyway.
The problem seems to be, that the LocationStrategy has to be defined within the providers array, as pointed out by SilverJan and KochFolie. See HashLocationStrategy not working as expected
it's works for me:
...
import { RouterModule, Routes } from '#angular/router';
import {
APP_BASE_HREF,
LocationStrategy,
HashLocationStrategy
} from '#angular/common';
...
const appRoutes: Routes = [
{ path: '', loadChildren: './user-profile/user-profile.module#UserProfileModule'},
...
];
#NgModule({
...
providers: [ { provide: APP_BASE_HREF, useValue: "/core/user" }, {provide: LocationStrategy, useClass: HashLocationStrategy}],
bootstrap: [AppComponent]
})
export class AppModule { }