ERROR in ./src/app/app.module.ts Module not found - angular2-routing

I'm working on angular-cli. I got following errors.
ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve '#angular/router/src/router_module' in
'E:\xampp\Angular-cli\Login\src\app'
# ./src/app/app.module.ts 13:0-69
# ./src/main.ts
# multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
I've this library #angular/router/src/router_module in my node_module. What is missing?
Here are required files.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { AdminAccount } from './admin/admin.component';
import { LoginForm } from './login/login.component';
import { FileData } from './filedata/filedata.component';
import { ROUTER_PROVIDERS } from "#angular/router/src/router_module";
import { RouterModule, Routes, ROUTES } from "#angular/router";
import { Http, Response } from "#angular/http";
import { Route } from './router/router.component';
#NgModule(
{
imports: [RouterModule ,Route, BrowserModule, Http, Response, AdminAccount, LoginForm, FileData, Route],
declarations: [AppComponent],
providers: [ROUTER_PROVIDERS],
bootstrap: [AppComponent]
})
export class AppModule { }
router.component.ts
import { Component, OnInit } from '#angular/core';
import { RouterModule } from "#angular/router";
import { LoginForm } from "../login/login.component";
import { AdminAccount } from "../admin/admin.component";
export const Route = RouterModule.forRoot(
[
{ path: '/', component: LoginForm },
{ path: '/admin', component: AdminAccount }
]);
app.component.ts
import { Component } from "#angular/core";
import { LoginForm } from "./login/login.component";
import { AdminAccount } from "./admin/admin.component";
import { Routes, RouterModule } from "#angular/router";
import { FileData } from "./filedata/filedata.component";
#Component(
{
selector: "root",
templateUrl: "./app.component.html",
})
export class AppComponent {}
If need more file let me know.

#Fahad Nasir Here's AdminAcount.
import { Component, OnInit } from '#angular/core';
import { Router } from "#angular/router";
#Component(
{
selector: "admin",
templateUrl: "./admin.component.html",
})
export class AdminAccount
{
adminUser = document.cookie.split("??")[0];
adminPass = document.cookie.split("??")[1];
constructor(public router: Router)
{
if (document.cookie !== undefined)
{
if (this.adminUser == "admin" && this.adminPass == "admin")
{
console.log("Welcome!");
}
else
{
this.router.navigate(["Loginform"]);
console.log("Redirect!");
}
}
else
{
console.log("Error: Undefined Login!");
}
}
}
Here Have a look

Related

Breadcrumbs in Angular don't show my children node details

I'm a beginner in Angular, and use BreadCrumb in my project. I have no problem with other pages, but when I want to show my child node details, I can only see the product id.
My project is here, and this is my code.
core.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import { RouterModule } from '#angular/router';
import { TestErrorComponent } from './test-error/test-error.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { ServerErrorComponent } from './server-error/server-error.component';
import { ToastrModule } from 'ngx-toastr';
import { BreadcrumbModule } from 'xng-breadcrumb';
import { SectionHeaderComponent } from './section-header/section-header.component';
#NgModule({
declarations: [NavBarComponent, TestErrorComponent, NotFoundComponent, ServerErrorComponent, SectionHeaderComponent],
imports: [
CommonModule,
RouterModule,
BreadcrumbModule,
ToastrModule.forRoot({
positionClass: 'toast-bottom-right',
preventDuplicates: true
})
],
exports: [NavBarComponent, SectionHeaderComponent]
})
export class CoreModule { }
shop.routing.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { Routes, RouterModule } from '#angular/router';
import { ShopComponent } from './shop.component';
import { ProductDetailsComponent } from './product-details/product-details.component';
const routes: Routes = [
{ path: '', component: ShopComponent },
{ path: ':id', component: ProductDetailsComponent, data: { breadCrumb: { alias: 'productDetails' } }}
];
#NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
export class ShopRoutingModule { }
product-details.component.ts:
import { Component, OnInit } from '#angular/core';
import { IProduct } from '../../shared/models/product';
import { ShopService } from '../shop.service';
import { ActivatedRoute } from '#angular/router';
import { BreadcrumbService } from 'xng-breadcrumb';
#Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
product: IProduct;
constructor(private shopService: ShopService, private activatedRoute: ActivatedRoute, private bcService: BreadcrumbService) { }
ngOnInit(): void {
this.loadProduct();
}
loadProduct() {
this.shopService.getProduct(+this.activatedRoute.snapshot.paramMap.get('id')).subscribe(product => {
this.product = product;
this.bcService.set('#productDetails', product.name);
}, error => {
console.log(error);
});
}
}
I gave my project link to check all of my code if you need it. Thanks for the help!
This happened when I debugged my project on chrome:
seems you have a typing error,
in shop-routing-module.ts it should be breadcrumbnot breadCrumb
data: { breadcrumb: { alias: 'productDetails' } },

Populating a child router-outlet Angular2 not working

The solution below was the first attempt as below.
Created app.module.ts and app.route.ts.
Created default for app.component.ts. The app.component router is working as expected so far for the first level routing.
Created a new module called Dashboard, with dashboard.module.ts and dashboard.routes.ts.
I imported the dashboard into the app.module.ts.
Created Sitebar,Header, and HeaderNav in the Dashboard.component.ts with child . But, no idea why the child navigation always shows in the first level router-outlet, instead of the child router-outlet.
Dashboard.component.ts code below.
<div class="wrapper">
<app-mydash-sidebar
[headerText]="'No Rush'"
[headerLink]="'http://www.bit-numbers.com'"
[headerLogoImg]="'/assets/img/angular2-logo-white.png'"
[backgroundColor]="'red'"
[backgroundImg]="'/assets/img/sidebar-5.jpg'"
[navItems]="navItems">
</app-mydash-sidebar>
<div class="main-panel">
<app-mydash-navbar [navItems]="navItems"></app-mydash-navbar>
<router-outlet ></router-outlet>
</div>
</div>
app.component.ts below.
<router-outlet></router-outlet>
Any idea?
app.routes.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { MembersComponent } from './members/members.component';
import { AuthGuard } from './auth.service';
import { SignupComponent } from './signup/signup.component';
import { EmailComponent } from './email/email.component';
import { HomeComponent } from './home/home.component';
import { BookingsComponent } from './bookings/bookings.component';
export const router: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'login-email', component: EmailComponent },
{ path: 'members', component: MembersComponent, canActivate: [AuthGuard] },
{ path: '', component: LoginComponent},
{ path: 'bookings', component: BookingsComponent },
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
mydash.routes.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard } from '../auth.service';
import { MydashBookingsComponent } from '../mydash/mydash-bookings/mydash-bookings.component';
import { MydashChartComponent } from '../mydash/mydash-chart/mydash-chart.component';
import { MydashDashboardComponent } from '../mydash-dashboard/mydash-dashboard.component';
export const Dashboardrouter: Routes = [
{
path: 'dashboard',
children: [{
path: '',
pathMatch: 'full',
component: MydashDashboardComponent
},
{
path: 'mybookings',
component: MydashBookingsComponent
}]
}
];
export const DashboardRouting: ModuleWithProviders = RouterModule.forChild(Dashboardrouter);
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 { AngularFireModule } from 'angularfire2';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { EmailComponent } from './email/email.component';
import { SignupComponent } from './signup/signup.component';
import { MembersComponent } from './members/members.component';
import { AuthGuard } from './auth.service';
import { routes } from './app.routes';
import { IconsComponent } from './icons/icons.component';
import { NotificationsComponent } from './notifications/notifications.component';
import { UserComponent } from './user/user.component';
import { MydashModule } from './mydash/mydash.module';
import { HomeComponent } from './home/home.component';
import { BookingsComponent } from './bookings/bookings.component';
import {FirebaseServiceService} from './services/firebase-service.service';
// Must export the config
export const firebaseConfig = {
...
};
#NgModule({
declarations: [
AppComponent,
LoginComponent,
EmailComponent,
SignupComponent,
MembersComponent,
IconsComponent,
NotificationsComponent,
UserComponent,
HomeComponent,
BookingsComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig),
MydashModule,
routes,
],
providers: [AuthGuard,FirebaseServiceService],
bootstrap: [AppComponent],
})
export class AppModule { }
mydash.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { MydashChartComponent } from './mydash-chart/mydash-chart.component';
import { MydashCheckboxComponent } from './mydash-checkbox/mydash-checkbox.component';
import { MydashCloseLayerComponent } from './mydash-close-layer/mydash-close-layer.component';
import { MydashFooterComponent } from './mydash-footer/mydash-footer.component';
import { MydashNavbarComponent } from './mydash-navbar/mydash-navbar.component';
import { MydashSidebarComponent } from './mydash-sidebar/mydash-sidebar.component';
import { MydashSidebarItemsComponent } from './mydash-sidebar-items/mydash-sidebar-items.component';
import { MydashTableComponent } from './mydash-table/mydash-table.component';
import { MydashTaskListComponent } from './mydash-task-list/mydash-task-list.component';
import { MydashUserProfileComponent } from './mydash-user-profile/mydash-user-profile.component';
import { MydashNavbarItemsComponent } from './mydash-navbar-items/mydash-navbar-items.component';
import { MydashBookingsComponent } from './mydash-bookings/mydash-bookings.component';
import { DashboardRouting} from './mydash.routes';
import { MydashDashboardComponent } from '../mydash-dashboard/mydash-dashboard.component';
export interface DropdownLink {
title: string;
routerLink?: string;
}
export enum NavItemType {
Sidebar = 1, // Only ever shown on sidebar
NavbarLeft = 2, // Left-aligned icon-only link on navbar in desktop mode, shown above sidebar items on collapsed sidebar in mobile mode
NavbarRight = 3 // Right-aligned link on navbar in desktop mode, shown above sidebar items on collapsed sidebar in mobile mode
}
export interface NavItem {
type: NavItemType;
title: string;
routerLink?: string;
iconClass?: string;
numNotifications?: number;
dropdownItems?: (DropdownLink | 'separator')[];
}
#NgModule({
imports: [
CommonModule,
DashboardRouting,
],
declarations: [
MydashChartComponent,
MydashCheckboxComponent,
MydashCloseLayerComponent,
MydashFooterComponent,
MydashNavbarComponent,
MydashSidebarComponent,
MydashSidebarItemsComponent,
MydashTableComponent,
MydashTaskListComponent,
MydashUserProfileComponent,
MydashNavbarItemsComponent,
MydashBookingsComponent,
MydashDashboardComponent],
// These components are to export to allow access from the Dashboard. Do it manually, not done by ng CLI.
exports: [
MydashSidebarComponent,
MydashNavbarComponent,
MydashFooterComponent,
MydashChartComponent,
MydashTaskListComponent,
MydashTableComponent,
MydashUserProfileComponent,
MydashCloseLayerComponent,
MydashBookingsComponent
],
providers:[]
})
export class MydashModule { }
I solved the issue. The problem was because the dashboard component was missing in the file name mydash.routes.ts. I assigned the appropriate component underneath the path: 'dashboard', before the Child routes. Now, it works like a champ. Cheers!
The Answer code below.
path: 'dashboard',
component: MydashDashboardComponent,
children: [{

Adding Dragular to Angular2 Application: document is not defined

I am fairly new to Angular2 and I am having issues adding Dragula to my application. When I run the application an error is thrown prior to loading the home page:
Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: document is not defined
The error message mentions Prerending which I suspect is in relation to the project using asp-prerender-module.
I've tried to follow official tutorials from Dragula and forum posts. Below are my app.module and component file snippets (... denotes summarised code):
app.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component'
...
import { SearchComponent } from './components/search/search.component';
import { BrowserModule } from '#angular/platform-browser';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { Injectable } from '#angular/core';
import { DragulaModule } from 'ng2-dragula';
#NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
...
SearchComponent
],
imports: [
UniversalModule,
BrowserModule,
FormsModule,
DragulaModule,
CommonModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
...
{ path: 'search', component: SearchComponent },
{ path: '**', redirectTo: 'home' }
])
]
})
export class AppModule {
}
search.component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { SearchService } from '../../services/search.service';
import { DragulaService } from 'ng2-dragula';
#Component({
selector: 'search',
template: require('./search.component.html'),
providers: [SearchService, DragulaService]
})
I suspect I am missing an a step when including Dragula, but I cannot figure out where. I have included both dragula (^3.7.2) and ng2-dragula (^1.3.0) in my package.json file.
your DragulaService initialization is wrong!! check Dragula documentation link
search.component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { SearchService } from '../../services/search.service';
import { DragulaService } from 'ng2-dragula';
#Component({
selector: 'search',
template: require('./search.component.html'),
providers: [SearchService]
})
expoert searchcomponent{
constructor(private dragulaService: DragulaService) {
console.log('DragulaService created');
}
}
Now you can play with drag and drop
If you want more control over drag and drop you can add events and options to dragulaService.
constructor(private dragulaService: DragulaService) {
dragulaService.drag.subscribe((value) => {
console.log(`drag: ${value[0]}`);
this.onDrag(value.slice(1));
});
dragulaService.drop.subscribe((value) => {
console.log(`drop: ${value[0]}`);
this.onDrop(value.slice(1));
});
dragulaService.over.subscribe((value) => {
console.log(`over: ${value[0]}`);
this.onOver(value.slice(1));
});
dragulaService.out.subscribe((value) => {
console.log(`out: ${value[0]}`);
this.onOut(value.slice(1));
});
}
private onDrag(args) {
let [e, el] = args;
// do something
}
private onDrop(args) {
let [e, el] = args;
// do something
}
private onOver(args) {
let [e, el, container] = args;
// do something
}
private onOut(args) {
let [e, el, container] = args;
// do something
}

Unable to broadcast messages from http extender class to App Component in Angular 2

project Structure
Error Information
This is the error i am getting , when i broadcast the message from http extender service to the app component.
Loading Interceptor(http extender)
this is my http extender ,i am unable to broadcast the messages to App component from here ,but i am able to broadcast the messages from the child components to App component ,please see the image for the error information and project structure
import { Injectable } from '#angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, ConnectionBackend } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { EventsEmitter } from './eventsEmitter';
#Injectable()
export class LoadingInterceptor extends Http {
private currentRequests: number = 0;
public constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions, private eventsEmitter: EventsEmitter) {
super(_backend, _defaultOptions);
}
public get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this.incrementRequestCount();
var response = super.get(url, options);
response.subscribe(null, error => {
this.decrementRequestCount();
}, () => {
this.decrementRequestCount();
});
return response;
}
private decrementRequestCount() {
if (--this.currentRequests == 0) {
this.eventsEmitter.broadcast('loading-complete');
}
}
private incrementRequestCount() {
if (this.currentRequests++ == 0) {
this.eventsEmitter.broadcast('loading-started');
}
}
}
App Component
I am listening the events broadcasted in the app component to show the loader gif on the screen
import { Component } from '#angular/core';
import { EventsEmitter } from './assets/scripts/services/eventsEmitter';
import { ToasterService } from 'angular2-toaster';
#Component({
selector: 'my-app',
templateUrl:'app/app.component.html'
})
export class AppComponent {
private toasterService: ToasterService;
private message: any;
private active: any;
constructor(toasterService: ToasterService, private eventsEmitter: EventsEmitter) {
this.toasterService = toasterService;
this.eventListners();
}
eventListners() {
this.eventsEmitter.on<string>('loading-complete')
.subscribe(message => {
this.active = false;
});
this.eventsEmitter.on<string>('loading-started')
.subscribe(message => {
this.active = true;
});
}
}
Event Emitter
this is the event emittter i am using to broadcast the events
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
interface EventsEmitterInterface {
key: any;
data?: any;
}
export class EventsEmitter {
private _eventBus: Subject<EventsEmitterInterface>;
constructor() {
this._eventBus = new Subject<EventsEmitterInterface>();
}
broadcast(key: any, data?: any) {
this._eventBus.next({ key, data });
}
on<T>(key: any): Observable<T> {
return this._eventBus.asObservable()
.filter(event => event.key === key)
.map(event => <T>event.data);
}
}
App Module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
import { HttpModule, JsonpModule, Http, RequestOptions, XHRBackend, RequestOptionsArgs, Response, ConnectionBackend} from '#angular/http';
import { AppRoutingModule } from './app.routes';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { LoadingInterceptor } from './assets/scripts/services/loadingInterceptor';
import { EventsEmitter } from './assets/scripts/services/eventsEmitter';
import { ToasterModule, ToasterService } from 'angular2-toaster';
#NgModule({
imports: [AppRoutingModule, BrowserModule, FormsModule, ReactiveFormsModule, HttpModule, JsonpModule, ToasterModule ],
declarations: [AppComponent, LoginComponent],
bootstrap: [AppComponent],
providers: [EventsEmitter,LoadingInterceptor,
{
provide: Http,
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, eventsEmitter: EventsEmitter) => new LoadingInterceptor(xhrBackend, requestOptions, eventsEmitter),
deps: [XHRBackend, RequestOptions]
},{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppModule { }
I am stuck here for many days, it would be really helpful if you could help me resolve this issue
You forgot to add EventsEmitter dependency within your useFactory provider:
deps: [XHRBackend, RequestOptions]
It shoul be:
deps: [XHRBackend, RequestOptions, EventsEmitter]
That's why your LoadingInterceptor constructor gets undefined for EventsEmitter dependency

Extending HTTP module in Angular2 throws error

I am trying to extend the Angular2 HTTP module in order to create an HTTP interceptor of sorts.. the only problem is when I try to extend this module I get the following error:
No provider for ConnectionBackend!
I have no idea why this is happening and can't seem to get this error to go.
Here is my custom HTTP module:
import { Injectable } from "#angular/core";
import { Http, ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response } from "#angular/http";
import { Observable } from "rxjs";
#Injectable()
export class HttpInterceptor extends Http {
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions
) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
console.log('request...');
return super.request(url, options).catch(res => {
// do something
});
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
console.log('get...');
return super.get(url, options).catch(res => {
// do something
});
}
}
And here is my app.module.ts file:
import 'app/rxjs-extensions';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule } from "#angular/http";
import { FormsModule } from "#angular/forms";
import { AuthGuard } from "./guards/auth.guard";
import { routing } from "./app.routing";
import { AppComponent } from './app.component';
import { HomeComponent } from "./components/home/HomeComponent";
import { LoginComponent } from "./components/login/LoginComponent";
import { NavBarComponent } from "./components/navbar/NavBarComponent";
import { ProductComponent } from "./components/catalog/products/ProductComponent";
import { GlobalEventsManager } from "./services/globalEventsManager.service";
import { AuthService } from "./services/auth.service";
import { ToastModule } from 'ng2-toastr/ng2-toastr';
import { LeftNavComponent } from "./components/left-nav/left-nav-component";
import { SettingsComponent } from "./components/settings/settings-component";
import { UsersComponent } from "./components/users/users-component";
import { OptionsComponent } from "./components/catalog/options/OptionsComponent";
import { CategoriesComponent } from "./components/catalog/categories/CategoriesComponent";
import { ManufacturersComponent } from "./components/catalog/manufacturers/ManufacturersComponent";
import { ProductSearchComponent } from "./components/catalog/products/directives/ProductSearchComponent";
import { ProductListComponent } from "./components/catalog/products/directives/ProductListComponent";
import { ProductService } from "./services/product.service";
import { HttpInterceptor } from "./services/HttpInterceptor.service";
#NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
routing,
ToastModule
],
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
NavBarComponent,
ProductComponent,
ProductSearchComponent,
ProductListComponent,
LeftNavComponent,
SettingsComponent,
UsersComponent,
OptionsComponent,
CategoriesComponent,
ManufacturersComponent
],
providers: [
AuthService,
AuthGuard,
GlobalEventsManager,
ProductService,
HttpInterceptor
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
I have tried placing the my HttpInterceptor module inside the providers array in this file and this still doesn't work. Can anyone tell me why this is not working?
Thanks!
You have to construct and provide your extended class yourself like so:
ProductService,
{
provide: HttpInterceptor,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) =>
new HttpInterceptor(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}
],
Also, if you want to inject another MyService in there, you can do
{
deps: [XHRBackend, RequestOptions, MyService],
provide: HttpInterceptor,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, myService: MyService) =>
new HttpInterceptor(backend, defaultOptions, myService),
},
After that, just inject MyService in the HttpInterceptor

Resources