I am having trouble injecting router into the constructor of the app.component.ts file, by calling "private router: Router".
It gives me the following error:
Error: "StaticInjectorError(AppModule)[AppComponent -> Router]:
StaticInjectorError(Platform: core)[AppComponent -> Router]:
NullInjectorError: No provider for Router!"
But when I remove the injection, the page works fine, but I cannot use the navigate function to load into other components.
Here is what I have
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';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/Router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [MessageParser]
})
export class AppComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {}
goToLobby() {
this.router.navigate(['lobby']);
}
}
app.component.html
<button (click)="goToLobby()">Go to lobby</button>
<router-outlet></router-outlet>
app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { MainComponent } from './main/main.component';
import { LobbyComponent } from './lobby/lobby.component';
import { GameComponent } from './game/game.component';
const appRoutes: Routes = [
{ path: '', component: MainComponent },
{ path: 'lobby', component: LobbyComponent },
{ path: 'game', component: GameComponent }
];
#NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
Remove RouterModule from your exports inside AppRoutingModule
#NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
]
})
Related
I created a new component with 'ng generate component', but after pressing navigating the url the target view doesn't load, I don't know why. The url will be changed correctly but the view will be not changed.
export class AppComponent {
title = 'Overview';
constructor(private router: Router) { }
onPressStart($event){
this.router.navigate(['/start']);
}
}
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 { StartComponent } from './start/start.component';
#NgModule({
declarations: [
AppComponent,
StartComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.mdoules.ts:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { StartComponent } from './start/start.component';
import {AppComponent} from './app.component';
const routes: Routes = [ {path: "", component:AppComponent}, {path: "start", component: StartComponent} ];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The AppComponent and StartComponent should not be siblings like you did.
AppComponent is bootstrapped, that means it's your root component and you should not try to load it with a route.
So just put a <router-outlet></router-outlet> inside AppComponent which will act as a placeholder for route-loaded components.
Then remove AppComponent from the routes, and all of your routes will work.
The following code is my viewall.ts code
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-viewall',
templateUrl: './viewall.component.html',
styleUrls: ['./viewall.component.css']
})
#Injectable()
export class RestComponent {
constructor(private http: HttpClient) { }
configUrl = "http://34.201.147.118:3001/getAllData";
getConfig() {
return this.http.get(this.configUrl);
}
}
This is my app.module.ts code
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {FormsModule} from'#angular/forms';
import { AppComponent } from './app.component';
import { RestComponent } from './rest/rest.component';
import { ViewallComponent } from './viewall/viewall.component';
import { HttpClientModule} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
RestComponent,
ViewallComponent
],
imports: [
BrowserModule,FormsModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
it is giving e the following error ERROR in src/app/app.module.ts(6,10): error TS2305: Module '"E:/paramount/paramount/src/app/viewall/viewall.component"' has no exported member 'ViewallComponent'.
Where is the exported class inside viewall.component.ts? You should be exporting a class from the component.
Haven't you declared RestComponent as Injectable and that too inside viewall.ts, and then you are importing it from rest.component file inside app.module.ts.
Try to move the RestComponent from the declarations array to providers array and also the import from the correct file.
Hope it helps.
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {FormsModule} from'#angular/forms';
import { AppComponent } from './app.component';
import { RestComponent } from './rest/rest.component';
import { ViewallComponent } from './viewall/viewall.component';
import { HttpClientModule} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
ViewallComponent
],
imports: [
BrowserModule,FormsModule,
HttpClientModule,
],
providers: [
RestComponent,
],
bootstrap: [AppComponent]
})
export class AppModule { }
Your viewall.component.ts should be exporting a class and look like this:-
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-viewall',
templateUrl: './viewall.component.html',
styleUrls: ['./viewall.component.css']
})
export class ViewallComponent{}
injectable service is in providers
you can try with this solution.
providers: [
RestComponent,
],
declarations: [
AppComponent,
ViewallComponent
],
In viewall component.ts
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-viewall',
templateUrl: './viewall.component.html',
styleUrls: ['./viewall.component.css']
})
export class ViewallComponent{
constructor() { }
}
#Injectable()
export class RestComponent {
constructor(private http: HttpClient) { }
configUrl = "http://34.201.147.118:3001/getAllData";
getConfig() {
return this.http.get(this.configUrl);
}
}
I am facing the problem in angular 4.4 , In my app, I have hierarchical view. In which I have created a
:= module 1 -> module 2 -> my component.
I have declared everything correctly. , But still I'm getting error.
Declared component.
Imported it into other module.
selector name is same.
Exported component in module 2.
Imported module 2 in module 1.
What could be the catch?
Component Code:
Admin -> Configuration -> mycomponent
//My component
import { Component, OnInit, ViewChild, ChangeDetectorRef } from '#angular/core';
#Component({
selector: 'test-mycomponent',
templateUrl: './mycomponent.component.html',
styleUrls: ['./mycomponent.component.scss']
})
export class MyComponentComponent implements OnInit {
#ViewChild('myComponentTable')
constructor() {
}
ngOnInit() {
//init functionality
}
}
// configure module code
import { NgModule,Component } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { MyComponentComponent } from './mycomponent/mycomponent.component';
#NgModule({
imports: [
CommonModule,
WidgetsModule,
FormsModule,
NgbModule
],
declarations: [
MyComponent
],
providers: [
],
exports: [
MyComponent
]
})
export class ConfigurationModule { }
//Main module admin
import { NgModule, Component } from '#angular/core';
import { CommonModule } from '#angular/common';
import { ConfigurationModule } from './configuration/configuration.module';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { MyComponentComponent } from './configuration/mycomponent/mycomponent.component';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
CommonModule,
NgbModule,
FormsModule,
ConfigurationModule
],
declarations: [
],
exports: [
]
})
export class AdminModule { }
and I am calling that template in another file
//Test file html
<ng-template>
<test-mycomponent></test-mycomponent>
</ng-template>
You are not declaring the right component the name should be MyComponentComponent in the declerations and exports:
import { MyComponentComponent } from './mycomponent/mycomponent.component';
declarations: [
MyComponent //should be MyComponentComponent
],
providers: [
],
exports: [
MyComponent //should be MyComponentComponent
]
Repo: https://github.com/leongaban/lifeleveler.io
Not sure why I'm getting this error, I have Router imported in my app.component.ts
I'm trying to use the app.component to hold the main <router-outlet>, and serve up the login view first.
app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { routing } from './app.routing';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { AuthService } from './shared/services/auth.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/throw';
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule,
routing
],
declarations: [
AppComponent,
LoginComponent
],
providers: [
AuthService,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { User } from './shared/models/user';
import { Router } from '#angular/router';
#Component({
selector: 'my-app',
templateUrl: './app/app.component.html',
styleUrls: ['./app/app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
}
}
app.component.html
<router-outlet></router-outlet>
app.routing.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './login/login.component';
export const routes: Routes = [
{
path: '',
redirectTo: '/login',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent
}
]
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
I just refactored your project with webpack , your same code works just fine:
github repo
first :
npm install -g #angular/cli
npm install
ng serve
It looks like you might be importing the RouterModule multiple times.
I would remove this line from your app.routing.ts
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
In your app.module I would import your routes with:
import { routes } from './app.routing';
And then import the RouterModule as:
RouterModule.forRoot(routes)
You should add the RouterModule.forRoot(routes) statement inside your AppModule:
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes)
],
declarations: [
AppComponent,
LoginComponent
],
providers: [
AuthService,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
and remove it from your app.routing.ts file:
export const routes: Routes = [
{
path: '',
redirectTo: '/login',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent
}
];
Just import RouterOutlet
import { RouterOutlet } from '#angular/router';
I have a component in angular 2 as shown below
login.component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`
})
export class HomeComponent {
}
The appModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'Account/Login', component: LoginComponent }
];
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule, RouterModule.forRoot(appRoutes)],
declarations: [LoginComponent, HomeComponent],
bootstrap: [HomeComponent]
})
export class AppModule { }
login.cshtml
#{
ViewData["Title"] = "Login";
}
<login-app>looding...</login-app>
partialLogin.cshtml
<router-outlet></router-outlet>
<p>THis is test</p>
Routing
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "spa-fallback",
template: "{*url}",defaults: new { controller = "Home", action = "Index" });
});
I have use the angular 2 routing as you can see in the appmodule.ts.If I navigate to homepage i,e Home/Index I will get an error as The selector "login-app" did not match any elements and when I navigate to Account/Login I will get an error as The selector "Home-app" did not match any elements.I know the the condition on appmodule is not working. How can I make this work. Please anyone can solve this issue
you are getting this error because you didn't import all your other component in you ngModule file. add them in declaration just like you have imported LoginComponent
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule],
declarations: [LoginComponent],<-- add all your component here
bootstrap: [LoginComponent]
})
export class AppModule { }
Below is an example of how to add route in Angular2:
//Create new app.module.ts file
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './Components/login.Component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'login', component: LoginComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
//Import the above define route in your App module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
//Import your route file
import { routing } from './app.routing';
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule,routing,],
declarations: [LoginComponent],
bootstrap: [LoginComponent]
})
export class AppModule { }
Finally the working code.Call the respective selector in HTML page
AppModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { ModuleWithProviders } from '#angular/core';
import { AppComponent} from "./app.component";
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', redirectTo: 'Home/Index', pathMatch: 'full' },
{ path: 'Account/Login', component: LoginComponent },
{ path: 'Home/Index', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, routing],
declarations: [AppComponent,LoginComponent, HomeComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.Component.ts
import { Component } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
#Component({
selector: 'main-app',
template: '<router-outlet></router-outlet>'
})
export class AppComponent { }
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
`
})
export class HomeComponent {
}
login.Component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}