Angular9 'No provided for ActivatedRoute' - javascript

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

Related

Angular 7 :Error with Angular routing **'router-outlet'** is not a known element: [duplicate]

This question already has answers here:
'router-outlet' is not a known element
(24 answers)
Closed 8 months ago.
I have tried to include all imports to the necessary files,But I have got the following error while compiling. How could I solve it?
I have generated four differnet commonents Menu,home,contact,and about.Additional to this thare are also Header component that will later help to contain the memu bar to switch between the differnt components.And also footer component.The app-routing.ts and routes.ts files are also attached with this file,which helps for routing purpose.
'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the
'#NgModule.schemas' of this component to suppress this message. ("<app-header></app-header>
[ERROR ->]<router-outlet></router-outlet>
<app-footer></app-footer>"): ng:///AppModule/AppComponent.html#1:0
at syntaxError (compiler.js:1021)
at TemplateParser.push../node_modules/#angular/compiler/fesm5 /compiler.js.TemplateParser.parse (compiler.js:14830)
at JitCompiler.push../node_modules/#angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (compiler.js:24018)
at JitCompiler.push../node_modules/#angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (compiler.js:24005)
at compiler.js:23948
at Set.forEach (<anonymous>)
at JitCompiler.push../node_modules/#angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (compiler.js:23948)
at compiler.js:23858
at Object.then (compiler.js:1012)
at JitCompiler.push../node_modules/#angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:23857)
routes.ts file
import { Routes } from '#angular/router';
import { MenuComponent } from '../menu/menu.component';
import { DishdetailComponent } from '../dishdetail/dishdetail.component';
import { HomeComponent } from '../home/home.component';
import { AboutComponent } from '../about/about.component';
import { ContactComponent } from '../contact/contact.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'menu', component: MenuComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
app-routing.module.ts file
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { routes } from './routes';
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [ RouterModule ],
declarations: []
})
export class AppRoutingModule { }
app.module.ts file
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { MatToolbarModule } from '#angular/material/toolbar';
import {MatListModule} from '#angular/material/list';
import {MatGridListModule} from '#angular/material/grid-list';
import {MatCardModule} from "#angular/material/card";
import {MatButtonModule} from "#angular/material/Button";
import { FlexLayoutModule } from '#angular/flex-layout';
import 'hammerjs';
import { AppComponent } from './app.component';
import { MenuComponent } from './menu/menu.component';
import { FooterComponent} from './footer/footer.component';
import { HeaderComponent} from './header/header.component';
import { DishdetailComponent } from './dishdetail/dishdetail.component';
import { HomeComponent } from './home/home.component'
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import {DishService} from './services/dish.service';
import {RouterModule} from '#angular/router';
import { AppRoutingModule } from './app-routing/app-routing.module';
#NgModule({
declarations: [
AppComponent,
MenuComponent,
DishdetailComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
AboutComponent,
ContactComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FlexLayoutModule,
MatToolbarModule,
MatGridListModule,
MatCardModule,
MatButtonModule,
MatListModule,
AppRoutingModule,
RouterModule
],`
`providers: [
DishService
],`
`bootstrap: [AppComponent]`
`})`
export class AppModule { }
app.component.html file
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
I see you are missing app-routing.module.ts inside the imports of AppModule
#NgModule({
imports: [
CommonModule,
routingModule
],
})
export class AppModule{ }
I noticed that in your app.module.ts file you have back ticks ``` in inappropriate places somewhere around providers & bootstrap array. I copied & pasted this from your own code so you can see it better:
...MatListModule,
AppRoutingModule,
RouterModule
],`
`providers: [
DishService
],`
`bootstrap: [AppComponent]`
`})`
export class AppModule { }
Do this:
Remove all the back ticks in the app.module.ts file like I have done below and restart your terminal. This should solve any problems you are having.
...MatListModule,
AppRoutingModule,
RouterModule
],
providers: [
DishService
],
bootstrap: [AppComponent]
})
export class AppModule { }
I copied and pasted your code and worked on the files you provided information about. With the back ticks removed, your code works fine here on my laptop. Here's the result in the gif below, route works properly & no errors in the console. Example with just home & menu components.
Final result:
I removed all other things that didn't relate to routing from your code so that it would be easier to detect errors. Here's my folder structure.
Folder structure:
And here are the contents of my files:
route.ts file:
import { Routes } from '#angular/router';
import { MenuComponent } from './menu/menu.component';
import { HomeComponent } from './menu/home.component';
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'menu', component: MenuComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
app.module.ts file:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { MenuComponent } from './menu/menu.component';
import { HomeComponent } from './menu/home.component';
import { AppRoutingModule } from './app-routing.module';
import { RouterModule } from '#angular/router';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
MenuComponent
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts file:
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
template: `
<router-outlet></router-outlet>
`
})
export class AppComponent {
}
app-routing.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import { routes } from './routes';
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [ RouterModule ],
declarations: []
})
export class AppRoutingModule { }
menu.component.ts:
import { Component } from '#angular/core';
#Component({
template: '<h1>Menu Component</h1>'
})
export class MenuComponent {
}
home.component.ts:
import { Component } from '#angular/core';
#Component({
template: '<h1>Home Component</h1>'
})
export class HomeComponent {
}
Like I said, once I removed those unnecessary back ticks from the app.module.ts, your code worked fined with no errors.
I have started everything from scratch.Then my issue was fixed.I don't exactly know where is my problem.But,probably I have made routes file in separate folder.Making routes file in app-routing folder, fixed my issue.

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!

How to use routing with module instead of component in Angular 10+

I successfully used component in routing but when i am using module instead of component in angular 10 i am getting a white screen.
I would be really thankful for any kind of help.
this is what i've been trying:
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { DashboardModule } from './components/dashboard/dashboard.module';
import { DashboardComponent } from './components/dashboard/dashboard.component';
const routes: Routes = [
{ path: '', loadChildren: () => DashboardModule }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Dashboard module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { DashboardComponent } from './dashboard.component';
#NgModule({
declarations: [
DashboardComponent
],
imports: [
CommonModule
]
})
export class DashboardModule { }
Dashboard Component:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
constructor() {
alert('asdf');
}
ngOnInit(): void {
}
}
Thanks
Lazy loaded feature modules have to have their child routes declared separately. For example:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { DashboardComponent } from './dashboard.component';
const routes: Routes = [
{
path: '',
component: DashboardComponent,
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DashboardRoutingModule { }
Also make sure to always load lazy modules like Emilien said before :)
loadChildren: () => import('./components/dashboard/dashboard.module').then(m => m.DashboardModule)

ERROR while adding custom module to parent app module in angular

I am trying to add new module to make my angular application more modular and for lazy loading.
app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule,BrowserXhr } from "#angular/http";
import { LabService } from './lab/lab.service';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { OphistoryModule } from './Ophistory/ophistory.Module' //after adding this module ERROR is thrown
#NgModule({
imports:[
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{path: 'labDetails/:labName',component:LabDetailsComponent},
{path:'showRoboLog/:labName',component:RoboLogComponent},
{path:'',component:LabComponent}
]),
OphistoryModule
],
declarations: [
AppComponent
],
bootstrap:[ AppComponent ]
})
export class AppModule {}
app.component
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { LabComponent } from './lab/lab.component';
import { LabService } from './lab/lab.service';
#Component({
selector: 'my-app',
template: `
<router-outlet></router-outlet>
`,
providers: [LabService]
})
export class AppComponent {
constructor() {
}
pageTitle: string = 'ABC';
}
The problem I am facing after adding the module OphistoryModule is an error message saying
my-app' is not a known element:
But when I give the same name to the selector of my newly added module it is working fine.
Here are the custom module and component
ophistory.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser'
import { OphistoryComponent } from './ophistory.component'
import {CommonModule} from '#angular/common'
#NgModule({
imports: [RouterModule.forChild([
{path: 'test',component:OphistoryComponent}
]),CommonModule],
declarations:[OphistoryComponent]
})
export class OphistoryModule {}
ophistory.component
import { Component } from '#angular/core'
import { LabService } from '../lab/lab.service'
#Component({
selector:'my-ap',
templateUrl:'./ophistory.component.html'
})
export class OphistoryComponent {
constructor (private _service:LabService){}
}
Can anyone confirm if it is a bug in angular 2 or any other solution you have?

Routes When Importing Not Working

I am currently attempting to add routing to my Angular 2 project. All of the components work, but when I add 'appRoutes' to my imports on app.module.ts , an error gets thrown saying
Uncaught TypeError: Cannot set property 'stack' of undefined
Here is my code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { appRoutes } from './app.router';
import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { AboutComponent } from './about/about.component';
import { ResumeComponent } from './resume/resume.component';
import { WorkComponent } from './work/work.component';
import { BlogComponent } from './blog/blog.component';
import { HomeComponent } from './home/home.component';
#NgModule({
declarations: [
AppComponent,
NavigationComponent,
AboutComponent,
ResumeComponent,
WorkComponent,
BlogComponent,
HomeComponent
],
imports: [
appRoutes,
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent, NavigationComponent, AboutComponent,
ResumeComponent, WorkComponent, BlogComponent, HomeComponent]
})
export class AppModule { }
app.router.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ResumeComponent } from './resume/resume.component';
import { WorkComponent } from './work/work.component';
import { BlogComponent } from './blog/blog.component';
import { HomeComponent } from './home/home.component';
export const appRoutes: Routes =[
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'about', component: AboutComponent },
{ path: 'resume', component: ResumeComponent },
{ path: 'work', component: WorkComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'home', component: HomeComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(appRoutes);
Any help would be appreciated. The page works until I add the appRoutes import, then it just sits on Loading...
You should not need ModuleWithProviders. Remove that from:
export const routes: ModuleWithProviders = RouterModule.forRoot(appRoutes);
i.e.
export const routes: RouterModule.forRoot(appRoutes);
and see if it works. (Also clean up by removing the import).
I was able to find the solution to my own problem. I deleted every component from bootstrap: [...] besides the AppComponent, but kept the other components in the declarations and it fixed the problem.

Categories

Resources