After adding a few lines of code I described below appears
I have a problem, when I try to compile Angular, I have this error:
ERROR in node_modules/#auth0/angular-jwt/index.d.ts:29:48 - error NG6005: JwtModule.forRoot returns a ModuleWithProviders type without a generic type argument. Please add a generic type argument to the ModuleWithProviders type. If this occurrence is in library code you don't control, please contact the library authors.
29 static forRoot(options: JwtModuleOptions): ModuleWithProviders;
~~~~~~~~~~~~~~~~~~~
src/app/app.component.html:9:1 - error NG8001: 'app-nav' is not a known element:
1. If 'app-nav' is an Angular component, then verify that it is part of this module.
2. If 'app-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
9 <app-nav></app-nav>
~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:8:16
8 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
src/app/app.component.html:10:1 - error NG8001: '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.
10 <router-outlet></router-outlet>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:8:16
8 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
src/app/nav/nav.component.html:3:33 - error NG8002: Can't bind to 'routerLink' since it isn't a known property of 'a'.
3 <a class="navbar-brand" [routerLink]="['/home']">Dating App</a>
~~~~~~~~~~~~~~~~~~~~~~~~
src/app/nav/nav.component.ts:8:16
8 templateUrl: './nav.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component NavComponent.
src/app/register/register.component.html:6:74 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.
6 <input type="text" class="form-control" required name="username" [(ngModel)]="model.username" placeholder="Username">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
src/app/register/register.component.html:11:78 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.
11 <input type="password" class="form-control" required name="password" [(ngModel)]="model.password" placeholder="Password">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
src/app/register/register.component.html:1:22 - error NG8003: No directive found with exportAs 'ngForm'.
1 <form #registerForm="ngForm" (ngSubmit)="register()">
~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
this i my index.d.ts
import { ModuleWithProviders, Provider } from '#angular/core';
export * from './src/jwt.interceptor';
export * from './src/jwthelper.service';
export * from './src/jwtoptions.token';
export interface JwtModuleOptions {
jwtOptionsProvider?: Provider;
config?: {
tokenGetter?: () => string | null | Promise<string | null>;
headerName?: string;
authScheme?: string;
whitelistedDomains?: Array<string | RegExp>;
blacklistedRoutes?: Array<string | RegExp>;
throwNoTokenError?: boolean;
skipWhenExpired?: boolean;
};
}
declare module "#angular/core" {
interface ModuleWithProviders<T = any> {
ngModule: Type<T>;
providers?: Provider[];
}
}
export declare class JwtModule {
constructor(parentModule: JwtModule);
static forRoot(options: JwtModuleOptions): ModuleWithProviders;
}
//# sourceMappingURL=index.d.ts.map
this is my app.module.ts:
import { MemberCardComponent } from './members/member-card/member-card.component';
import { appRoutes } from './routes';
import { ErrorInterceptorProvider } from './_services/error.interceptor';
import { AuthService } from './_services/auth.service';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {HttpClientModule} from '#angular/common/http';
import {FormsModule, } from '#angular/forms';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { RouterModule } from '#angular/router';
import { JwtModule } from '#auth0/angular-jwt';
import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
import { MemberListComponent } from './members/member-list/member-list.component';
import { ListsComponent } from './lists/lists.component';
import { MessagesComponent } from './messages/messages.component';
// tslint:disable-next-line:typedef
export function tokenGetter(){
return localStorage.getItem('token');
}
#NgModule({
declarations: [
AppComponent,
NavComponent,
RegisterComponent,
HomeComponent,
MemberListComponent,
ListsComponent,
MessagesComponent,
MemberCardComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
BsDropdownModule.forRoot(),
RouterModule.forRoot(appRoutes),
JwtModule.forRoot({
config: {
// tslint:disable-next-line:object-literal-shorthand
tokenGetter: tokenGetter,
whitelistedDomains: ['localhost:5000'],
blacklistedRoutes: ['localhost:5000/api/auth']
}
}),
],
providers: [
AuthService,
ErrorInterceptorProvider
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Tt only adds that to app.module.ts:
// tslint:disable-next-line:typedef
export function tokenGetter(){
return localStorage.getItem('token');
}
and
JwtModule.forRoot({
config: {
// tslint:disable-next-line:object-literal-shorthand
tokenGetter: tokenGetter,
whitelistedDomains: ['localhost:5000'],
blacklistedRoutes: ['localhost:5000/api/auth']
}
}),
As I add this JWT module and try to add it to the project file I can't compile it if the problem is with the Angular version or it's something else.
I can't compile my program, How can I solve this problem.;/
Related
I am learning building application using angular and asp.net core using these videos on this link. Everything works fine except the edit of a component. If I give a URL like below, it goes to the route for error in app-routing.module.ts even though there's no error in the browser console log.
http://localhost:4200/genres/edit/1
The app-routing.model.ts is as below
import { Component, NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { CreateActorComponent } from './actors/create-actor/create-actor.component';
import { EditActorComponent } from './actors/edit-actor/edit-actor.component';
import { IndexActorsComponent } from './actors/index-actors/index-actors.component';
import { CreateGenreComponent } from './genres/create-genre/create-genre.component';
import { EditGenreComponent } from './genres/edit-genre/edit-genre.component';
import { IndexGenresComponent } from './genres/index-genres/index-genres.component';
import { HomeComponent } from './home/home.component';
import { CreateMovieTheaterComponent } from './movie-theaters/create-movie-theater/create-movie-theater.component';
import { EditMovieTheaterComponent } from './movie-theaters/edit-movie-theater/edit-movie-theater.component';
import { IndexMovieTheaterComponent } from './movie-theaters/index-movie-theater/index-movie-theater.component';
import { CreateMovieComponent } from './movies/create-movie/create-movie.component';
import { EditMovieComponent } from './movies/edit-movie/edit-movie.component';
const routes: Routes = [
{path:' ', component:HomeComponent},
{path:'genres', component:IndexGenresComponent},
{path:'genres/create', component:CreateGenreComponent},
{path:'genres/edit:id', component:EditGenreComponent},
{path:'actors', component:IndexActorsComponent},
{path:'actors/create', component:CreateActorComponent},
{path:'actors/edit:id', component:EditActorComponent},
{path:'movietheaters', component:IndexMovieTheaterComponent},
{path:'movietheaters/create', component:CreateMovieTheaterComponent},
{path:'movietheaters/edit:id', component:EditMovieTheaterComponent},
{path:'movies/create', component:CreateMovieComponent},
{path:'movies/edit:id', component:EditMovieComponent},
// {path:'**',component:HomeComponent}
{path:'**',redirectTo:' '}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
edit-genre.component.ts is
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { genreCreationDTO } from '../genres.model';
#Component({
selector: 'app-edit-genre',
templateUrl: './edit-genre.component.html',
styleUrls: ['./edit-genre.component.css']
})
export class EditGenreComponent implements OnInit {
constructor(private activatedRoute:ActivatedRoute) { }
model: genreCreationDTO={name:"Drama"};
ngOnInit(): void {
this.activatedRoute.params.subscribe(params=>{
});
}
//Event emiited value passed from child form-genre-creation to parent create-genre.component
//to be displayed
saveChanges(genreCreationDTO:genreCreationDTO)
{
}
}
edit-genre.component.html is
<h2>Edit Genre</h2>
<app-form-genre [model]="model" (onSaveChanges)="saveChanges($event)"></app-form-genre>
form-genre.component.html is
<form (submit)="saveChanges()" [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Name*</mat-label>
<input matInput formControlName="name">
<mat-error *ngIf="form.invalid">{{getErrorMessageFieldName()}}</mat-error>
</mat-form-field>
<div>
<button mat-flat-button color="primary" [disabled]="form.invalid">Save Changes</button>
<a mat-stroked-button routerLink="/genres">Cancel</a>
</div>
form-genre.component.ts is
import { Component, OnInit, Output,EventEmitter, Input } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { firstLetterUppercase } from 'src/app/validators/firstLetterUppercase';
import { genreCreationDTO } from '../genres.model';
#Component({
selector: 'app-form-genre',
templateUrl: './form-genre.component.html',
styleUrls: ['./form-genre.component.css']
})
export class FormGenreComponent implements OnInit {
constructor(private router: Router, private formBuilder:FormBuilder) { }
#Input()
model!: genreCreationDTO;
//Event Emitter
#Output()
onSaveChanges: EventEmitter<genreCreationDTO>=new EventEmitter<genreCreationDTO>();
form!: FormGroup;
ngOnInit(): void {
this.form= this.formBuilder.group({
name:['',[Validators.required, Validators.minLength(3),firstLetterUppercase()]]
});
if(this.model!==undefined){
this.form.patchValue(this.model);
}
}
getErrorMessageFieldName()
{
const field= this.form.get("name");
if(field?.hasError("required"))
{
return "The name field is required";
}
if(field?.hasError("minLength")){
return "The minimum length is 3"
}
if(field?.hasError('firstLetterUppercase')){
return field.getError('firstLetterUppercase').message;
}
return '';
}
saveChanges()
{
//Emit value from child form-genre.compnent to parent create-genre.component
this.onSaveChanges.emit(this.form.value);
// this.router.navigate(['/genres']);
}
}
I am new to .net core framework & angular and i'm using forms(chapter sharing forms) in the video tutorial by Felipe galivan. Everytime I give an edit/id url for a component, it keeps using this
{path:'**',redirectTo:' '}
in the app-routing.module.ts as if say genres/edit/id has no match. I'm doing exactly as Felipe in the video, mine keeps redirecting me to home page instead of genres/edit. Why is this happening?
I am fairly new to Angular 2 and having a problem with Routing. I have just started to explore the Routing. I will explain the structure and what I have achieved so far,
app.router.ts
import { ModuleWithProviders } from '#angular/core'
import { Routes, RouterModule } from '#angular/router'
import { AppComponent } from './app.component';
import { LoginComponent } from "../app/login/login.component"
export const router: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: AppComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import {UiSwitchModule} from 'angular2-ui-switch'
import { AppComponent } from './app.component';
import { AllReportsComponent } from "../app/all-reports/all-reports.component"
import { AvailableReportsComponent } from "../app/available-reports/available-reports.component"
import { NextReportsComponent } from "../app/next-reports/next-reports.component"
import { UrlsComponent } from "../app/urls/urls.component"
import { LoginComponent } from "../app/login/login.component"
import { TaskApi } from "../app/api/TaskApi"
import { routes } from "../app/app.router"
#NgModule({
imports: [
BrowserModule,
FormsModule,
UiSwitchModule,
HttpModule,
routes
],
declarations: [
AppComponent,
AllReportsComponent,
AvailableReportsComponent,
NextReportsComponent,
UrlsComponent,
LoginComponent
],
bootstrap: [AppComponent]
})
export class AppModule {
}
app.html
<div>
<all-reports></all-reports>
<available-reports></available-reports>
<next-reports></next-reports>
<urls></urls>
</div>
app.component.ts (very simple)
import { Component } from "#angular/core"
#Component({
templateUrl: '../app/app.html'
})
export class AppComponent {
}
and login.component.ts
import { Component } from '#angular/core';
import { TaskApi } from '../api/TaskApi';
import * as models from '../model/models';
#Component({
styleUrls: ['/app/css/login.css'],
templateUrl: '../../app/login/login.html',
providers: [TaskApi]
})
export class LoginComponent {
}
Now it can be seen that I am using multiple directives on app.html and all the respective components are working fine.
The problem I am facing is when I introduce Routing then I am able to understand where to use "router-outlet". I have used it on Index.html but it does not work and gives error about ng-component. So to just test around I have used following in Index.html,
<body>
<base href="/">
<ng-component></ng-component>
</body>
After I do this then my AppComponent is displayed by default where the LoginComponent should be displayed by default. On console, It also gives me error "Error: Cannot find primary outlet to load 'LoginComponent'"
Kindly guide me if I am using 4 directives on App.html as mentioned above then in that case how the routing will work. To summarize, I want to display Login page on localhost:3009/login and localhost:3009 and I want to display Home page (app.html) in localhost:3009/dashboard and app.html is using 4 directives to display 4 child components on it.
Angular Routing
Since Angular is single page application the routing functionality
helps to display different view in single page.
How to use router to change view?
since app.component.html is main view for most user. Iam also consider app.component.html as main view.
Router-outlet
Router-outer helps to load the change in our angular application.
app.component.html
<router-outlet></router-outlet>
Set AppComponent Default page as router-outlet and create new Dashboard.component.html in your main view.
router.ts
import { ModuleWithProviders } from '#angular/core'
import { Routes, RouterModule } from '#angular/router'
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard.component';
import { LoginComponent } from "../app/login/login.component"
export const router: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', redirectTo: '', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
The problem with your code is that there is no 'router-outlet', so angular doesn't understand where to display the view.
The 'router-outlet' directive marks where the router displays a view.
In your code, since in app.component.ts you are using app.html so you should use <router-outlet> </router-outlet> in that HTML file.
Your app.html file should look like this:
<router-outlet> </router-outlet>
These below things should not be used in the app component HTML file. They should be used in their the corresponding components.
<all-reports></all-reports>
<available-reports></available-reports>
<next-reports></next-reports>
<urls></urls>
For further understanding, please refer to the official documentation of Angular2. They have explained it pretty well here https://angular.io/docs/ts/latest/guide/router.html
i have been working with a product list Project and while configuring routes to navigate between different views, I get a red squiggly under the '#Routes' decorator and when i hover over the Routes, it says 'Routes only refers to a type, but is being used as a value here'. I researched in so many sights including here and tried many different ways to resolve this but I could not find out the issue.
app.component.ts
import { Component } from '#angular/core';
import { ProductListComponent } from './products/product-list.Component';
import { ProductService } from './products/product.service'
import { Routes } from '#angular/router';
import 'rxjs/Rx'; // Load all features
import { WelcomeComponent } from './home/welcome.component'
#Component({
selector: 'pm-app',
template: `
<div>
<nav class='navbar navbar-default'>
<div class='container-fluid'>
<a class='navbar-brand'>{{pageTitle}}</a>
<ul class='nav navbar-nav'>
<li><a>Home</a></li>
<li><a>Product List</a></li>
</ul>
</div>
</nav>
</div>
` ,
entryComponents : [ProductListComponent],
providers: [ProductService]
})
#Routes([
{ path: '/welcome' , name: 'Welcome' , component: WelcomeComponent, useAsDefault: true},
{ path: '/products' , name: 'Products' , component: ProductListComponent }
])
export class AppComponent {
pageTitle:string = 'Acme Product Management';
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { ProductListComponent } from './products/product-list.Component';
import { HttpModule } from "#angular/http";
import { RouterModule } from '#angular/router'
import { ProductFilterPipe } from './products/product-filter.pipe';
import { StarComponent } from './shared/star.component';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule,FormsModule,HttpModule,RouterModule],
declarations: [ AppComponent,ProductListComponent,ProductFilterPipe,StarComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
welcome.compnent.ts
import { Component } from '#angular/core';
#Component({
templateUrl: 'app/home/welcome.component.html'
})
export class WelcomeComponent {
public pageTitle: string = 'Welcome';
}
I think my coding is fine. But unable to get the expected result. Please Help!
Found out, the issue is... with RC5, Routes is an array of path's & is no more a Decorator, and you have to import 'RouterModule' instead of 'provideRouter'. While exporting you have to use 'RouterModule.forRoot'.
Also with RC5, we no longer specify the string name of the component while configuring routes instead we only specify the path & component only. And we no longer use the prefix '/' for the path. Also we no longer using useAsDefault instead we use redirectTo property to configure the default path.
I have used a separate module to do my route configurations instead of doing it in the root component as earlier. An updated version of my route configuration is given as below. Hope this will be helpful.
app.routes.ts
import { Routes, RouterModule } from '#angular/router';
import { ProductListComponent } from './products/product-list.Component';
import { WelcomeComponent } from './home/welcome.component'
import { ProductDetailComponent } from './products/product- detail.component';
const routes: Routes = [
{
path: 'welcome' ,
component: WelcomeComponent,
},
{
path: 'products' ,
component: ProductListComponent
},
{
path: 'product/:id' ,
component: ProductDetailComponent
},
{
path:'',
redirectTo:'/welcome',
pathMatch:'full'
},
];
export const routing = RouterModule.forRoot(routes);
I am developing Angular 2 application that is using KendoUI datagrid in asp.net web application. I have set index.html as the startup page. When i press F5, index.html loads. Click on the Risks Menu displays the datagrid with data that is defined in risk-list.component.html page. Its URL is localhost/risks. If I press F5, I get 404 page not found error. Could somebody tell me what the problem could be and how can I fix it?
This is my code:
risk-list.Component.ts
import { Component, OnInit } from '#angular/core';
import { Risk } from './risk';
import { RiskService } from './risk.service';
#Component({
moduleId: module.id,
selector: 'rm-risks',
templateUrl: '/app/risk-list.component.html',
providers: [RiskService]
})
export class RiskListComponent implements OnInit {
title = 'Risk List';
risks: Risk[];
constructor(private _riskService: RiskService) {
console.log(this.risks);
}
getRisks(): void {
this._riskService.getRisks().then(risks => this.risks = risks);
}
ngOnInit(): void {
this.getRisks();
}
};
risk-list.component.html
<kendo-grid [data]="risks">
<kendo-grid-column field="reference" title="Reference" width="120">
</kendo-grid-column>
<kendo-grid-column field="insuredName" title="Insured Name">
</kendo-grid-column>
<kendo-grid-column field="inceptionDate" title="Inception Date" width="230">
</kendo-grid-column>
<kendo-grid-column field="riskType" title="Risk Type" width="120">
</kendo-grid-column>
<kendo-grid-column field="Status" title="Status">
</kendo-grid-column>
<kendo-grid-column field="grossPremium" title="Gross Premium" width="230">
</kendo-grid-column>
<kendo-grid-column field="allocatedTo" title="Allocated To" width="120">
</kendo-grid-column>
<kendo-grid-column field="allocatedCompany" title="Allocated Company">
</kendo-grid-column>
<kendo-grid-column field="Discontinued" width="120">
<template kendoCellTemplate let-dataItem>
<input type="checkbox" [checked]="dataItem.Discontinued" disabled />
</template>
</kendo-grid-column>
</kendo-grid>
risk.service.ts
import { Injectable } from '#angular/core';
import { Risk } from './risk';
import { Risks } from './mock-risk';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
#Injectable()
export class RiskService {
getRisks(): Promise<Risk[]> {
return Promise.resolve(Risks);
}
}
risk.ts
export class Risk {
riskId: number;
reference: string;
insuredName: string;
inceptionDate: string;
riskType: string;
status: string;
grossPremium: number;
allocatedTo: string;
allocatedCompany: string;
}
mock-risk.ts
import { Risk } from './risk'
export const Risks: Risk[] = [
{
"riskId": 1,
"reference": "HISC9308336",
"insuredName": "SA 84161",
"inceptionDate": "March 19, 2016",
"riskType": "Quote",
"status": "Indication",
"grossPremium": 100,
"allocatedTo": "Broker User",
"allocatedCompany": "Broker"
},
{
riskId: 2,
reference: "HISC9308337",
insuredName: "SA 84161",
inceptionDate: 'April 22, 2016',
riskType: 'Quote',
status: 'Indication',
grossPremium: 300,
allocatedTo: 'Broker User',
allocatedCompany: 'Broker'
}
];
risks.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { RiskListComponent } from './risk-list.component';
import { RiskService } from './risk.service';
import { RiskRoutingModule } from './risks-routing.module';
import { GridModule } from '#progress/kendo-angular-grid';
#NgModule({
imports: [
CommonModule,
FormsModule,
RiskRoutingModule,
GridModule
],
declarations: [
RiskListComponent
],
providers: [
RiskService
]
})
export class RisksModule { }
risks-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { RiskListComponent } from './risk-list.component';
#NgModule({
imports: [
RouterModule.forChild([
{ path: 'risks', component: RiskListComponent }
])
],
exports: [
RouterModule
]
})
export class RiskRoutingModule { }
app.component.html
<h1>Angular Router</h1>
<nav>
<a routerLink="/risks" routerLinkActive="active">Risks</a>
</nav>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '#angular/core';
#Component({
moduleId: module.id,
selector: 'my-app',
templateUrl:'/app/app.component.html'
})
export class AppComponent { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { RiskListComponent } from './risk-list.component'
import { HomeComponent } from './home.component'
#NgModule({
imports: [
RouterModule.forRoot([
{ path: '', component: HomeComponent }
])
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
main.ts
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
This problem is solved by implementing HashLocationStrategy which adds # to all your routes. For example, http://localhost/myComponent becomes http://localhost/#/myComponent. You achieve this by adding HashLocationStrategy to AppModule's providers:
{ provide: LocationStrategy, useClass: HashLocationStrategy }
Of course, you need to import LocationStrategy and HashLocationStrategy from #angular/common:
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
For more information, check Angular 2 Router & Navigation - Browser URL Styles.
When the browser is refreshed it will send a get request to the server with the current url, since angular is using HTML 5 style navigation, the url will make no sense to the server. Either update your server to serve the index.html on particular paths or use the HashLocationStrategy.
The benefit of using HTML 5 style navigation is that you can mix your angular app with server rendered pages.
An example of getting this working with asp.net: http://blog.johnnyreilly.com/2015/05/a-tale-of-angular-html5mode-aspnet-mvc.html
More reading on angular: https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles
The best way to get rid of this Error404 page not found, you should import HashLocationStrategy to appModule.ts
When I previously worked on Angular, Same type of error raised in my Project, so that I created a simple repository for this kind of error (404 Page Not Found), it may help you. Here is the link -> AngularAppExample
I'm playing with angular2 and meteor (i'm new with both) and i'd like to change route if i can find a certain document in a collection. I read in the Angular 2 Meteor tutorial that the class MeteorComponent has methods subscribe and autorun so i'm trying to use this methods to get the job done (not sure if this is the best way to do it - i didn't remove autopublish).
But right now it isn't working.
My component is:
import {View, OnInit, Component} from 'angular2/core'
import {MeteorComponent} from 'angular2-meteor'
import {Navbar} from 'client/navbar/navbar'
import {FakePlayground} from 'client/intro/fake-playground/fake-playground'
import {PlayerList} from 'client/player-list/player-list'
import {PlayerService} from 'client/player/player-service'
import {Player} from 'client/player/player'
import {ProtectedDirective} from 'client/directives/protected-directive'
import {SentInvitation} from 'client/invitation/sent-invitation'
import {ReceivedInvitation} from 'client/invitation/received-invitation'
import {Invitations} from 'lib/invitations'
import {Router} from 'angular2/router'
#Component({
selector: 'intro'
})
#View({
templateUrl: 'client/intro/intro.html',
directives: [
Navbar,
PlayerList,
FakePlayground,
ProtectedDirective,
SentInvitation,
ReceivedInvitation
]
})
export class Intro extends MeteorComponent implements OnInit {
currentPlayer: Player
invitation: Mongo.Cursor<Object>
constructor(
public playerService: PlayerService,
private _router:Router
) {
super()
}
getInvitation() {
this.subscribe('invitations', () => {
this.invitation = Invitations.find({$or: [
{$and: [
{"sender._id": this.currentPlayer._id},
{status: 1}
]},
{$and: [
{"recipient._id": this.currentPlayer._id},
{status: 1}
]}
]})
this.autorun(() => {
console.log('autorun')
if(this.invitation){
console.log('game started')
this._router.navigate(['Game'])
}
})
})
}
getPlayer() {
this.currentPlayer = this.playerService.getCurrentPlayer()
}
ngOnInit() {
this.getPlayer()
this.getInvitation()
}
}
And in my fantasy getInvitation() called in ngOnInit should subscribe to
'invitations' collection and autorun() should check if the document is found and if it's found should change route.
But i'm not getting errors neither the route change.
Which should be the right way to change the route reactively to collection change?
Well, i was using this.autorun() the worng way.
It was much simpler:
import {View, OnInit, Component} from 'angular2/core'
import {MeteorComponent} from 'angular2-meteor'
import {Navbar} from 'client/navbar/navbar'
import {FakePlayground} from 'client/intro/fake-playground/fake-playground'
import {PlayerList} from 'client/player-list/player-list'
import {PlayerService} from 'client/player/player-service'
import {Player} from 'client/player/player'
import {ProtectedDirective} from 'client/directives/protected-directive'
import {SentInvitation} from 'client/invitation/sent-invitation'
import {ReceivedInvitation} from 'client/invitation/received-invitation'
import {Invitations} from 'lib/invitations'
import {Router} from 'angular2/router'
#Component({
selector: 'intro'
})
#View({
templateUrl: 'client/intro/intro.html',
directives: [
Navbar,
PlayerList,
FakePlayground,
ProtectedDirective,
SentInvitation,
ReceivedInvitation
]
})
export class Intro extends MeteorComponent implements OnInit {
currentPlayer: Player
constructor(
public playerService: PlayerService,
private _router:Router
) {
super()
}
getPlayer() {
this.currentPlayer = this.playerService.getCurrentPlayer()
}
ngOnInit() {
this.getPlayer()
this.autorun(() => {
if (Invitations.findOne({
$or: [
{$and: [{"sender._id": this.currentPlayer._id},{status: 1}]},
{$and: [{"recipient._id": this.currentPlayer._id},{status: 1}]}
]
})) {
this._router.navigate(['Game'])
}
})
}
}