Always I trying to GET '/' it shows static-root-component (component of my main page),
but when it is '/welcome' page immediately redirecting to '/' and also loading static-root-component instead of welcome-component
Initially I wanted to redirect users to welcome page if they aren't authorized, but login status only can be checked within JavaScript. After JS got info about login status it decides to redirect using location.replace("/welcome"), but... Angular again goes to '/'
"Funny" fact: there isn't any routing problems during debug with ng serve but it always happens with ng build
I don't know what's gone wrong and there is app.module.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StaticRootComponent } from './static-root/static-root.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { HttpClientModule } from '#angular/common/http';
import { HttpService } from './http.service';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
const appRoute: Routes = [
{ path: '', component: StaticRootComponent, pathMatch: 'full' },
{ path: 'welcome', component: WelcomeComponent }
];
#NgModule({
declarations: [
AppComponent,
StaticRootComponent,
WelcomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
RouterModule.forRoot(appRoute),
HttpClientModule
],
providers: [HttpService],
bootstrap: [AppComponent]
})
export class AppModule { }
I can drop any other Angular file if needed
In your code, change like below
const appRoute: Routes = [
{ path: '', component: StaticRootComponent },
{ path: 'welcome', component: WelcomeComponent },
{ path: '**', redirectTo: '' }
];
In the component file, inject this like below
import { Router } from '#angular/router';
constructor(
private router: Router
) {}
When you want do navigation use the below code instead of location.replace("/welcome")
this.router.navigate(['/welcome']);
Check the Module you trying to instantiate in the constructor of the Component linked to the Routing Path you are trying to access
In this case:
Our Component: example.component.ts
Our Module: HttpClientModule that contains HttpClient
Our Routing Path: "/example"
and make sure that Module is already existing in the app.module.ts , here is an example:
example.component.ts
import {HttpClient} from '#angular/common/http'; //child of HttpClientModule
#Component({selector: 'app-example',templateUrl: './example.component.html', styleUrls: ['./example.component.css']})
export class ExampleComponent{
constructor(private httpClient: HttpClient) { }
}
now let's see both examples of app module with and without the Module import and see the difference
app.module.ts
Without including HttpClientModule in imports array
import { AppComponent } from './app.component';
#NgModule({
declarations: [...],
imports: [BrowserModule,...],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this case loading the "/example" path will redirect you to the main page path which is usually "/" and that's because example.component.ts is using HttpClient (child of HttpClientModule) but not finding it in app.module.ts .
app.module.ts
Including HttpClientModule in imports array
import { AppComponent } from './app.component';
import { HttpClientModule} from '#angular/common/http'; //Import that module you willing to use
#NgModule({
declarations: [...],
imports: [BrowserModule,HttpClientModule,...], //add the module we currently using
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this case loading the "/example" path will work properly since we added the required module in app.module.ts.
If that's your case that would definitely fix your problem unless you have something else forcing the redirection to home page "index.html" or any other path, else if that didn't fix your problem read the following notes:
Make sure to check there are no redirections in the app-routing.module.ts routes array like this
const routes: Routes = [
{path: 'example', component: ExampleComponent},
{ path: '/example', redirectTo: '' }
];
it should only be like so
const routes: Routes = [
{path: 'example', component: ExampleComponent}
];
Also make sure there is no routing behaviour causing the redirection like #angular/router through something like this.router.navigate(['/'])
PS: SAME ISSUE COULD IMPLY IF YOU USING A SERVICE THAT'S USING A MODULE WHICH IS NOT ADDED TO MODULE IMPORTS IN app.module.ts
My project based on MEAN (Mongo, Express, Angular and NODEJS)... The last was a source of problem
#Shakthifuture, you said you want to see full code and I started answering:
"What you wanna to see else? My data and server files doesn't affec..."
and I've starting think "what if affect?": routing in whole of project works by Angular, but all new connection to the site pass NodeJS and Express, so I forgot about 404 case...
THE PROBLEM:
In server script file index.js of project's root folder a long time ago I've added code about what to do if entered path not found:
app.use(function (req, res, next) {
res.redirect('/');
// IF 404 NOT FOUND
});
and above of it something like:
app.get('/', function (req, res) {
res.sendFile(`${__dirname}/angular/index.html`)
});
// send index if path is '/'
but nothing for '/welcome', that's why redirecting happens
THE SOLUTION:
let's add the '/welcome' handler:
app.get('/welcome', function (req, res) {
res.sendFile(`${__dirname}/angular/index.html`)
});
(again index.html due to SPA)
Related
I have an Angular SSR app that is not able to render the homepage via localhost:4000 while the backend node server is running.
So if I go to localhost:4000 it will start loading but never display anything nor finished loading. However, if I go to another page like 404 where I have a button to take me to the home page it does load it. Additionally, if I turn off the backend server it does load the homepage.
The app routes are handled like this:
//app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { GuardDashboardGuard } from './guard-dashboard.guard';
import { KYCGuard } from './guard-kyc.guard';
// More imports for other paths
const routes: Routes = [
{
path: 'profile-update',
canActivate: [GuardDashboardGuard, KYCGuard],
loadChildren: () =>
import('./pages/profile-update/profile-update.module').then((m) => m.ProfileUpdatePageModule),
},
// More paths with the same structure
{
path: '',
loadChildren: () => import('./pages/home/home.module').then((m) => m.HomePageModule),
},
{
path: 'faqs',
loadChildren: () => import('./pages/faq/faq.module').then((m) => m.FaqPageModule),
},
{
path: '',
redirectTo: '/',
pathMatch: 'full',
},
{ path: '**', redirectTo: '404' },
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
scrollOffset: [0, 0],
anchorScrolling: 'enabled',
relativeLinkResolution: 'legacy',
initialNavigation: 'enabledBlocking',
}),
],
exports: [RouterModule],
})
export class AppRoutingModule { }
I have tried fully deleting path: '', and the app redirected localhost:4000 to profile-update. Even if i delete profile-update I am still redirected to a Update Profile page.
Home page directory tree looks like:
.
├── home-routing.module.ts
├── home.module.ts
├── home.page.html
└── home.page.ts
// home-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomePage } from './home.page';
const routes: Routes = [
{
path: '',
component: HomePage,
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class HomePageRoutingModule {}
I am not sure what the cause of this error is or what code is relevant so I don't know what other code should be included in my question.
I also get a network error of crbug/1173575, non-JS module files deprecated.
and have found this Crbug/1173575, non-JS module files deprecated. chromewebdata/(index)꞉5305:9:5551 which was not very helpful to solve thebug.
I am new to Angular, and wanted to have a page with the directory of /cities/denver. I have the file structure
|-- app
|-- app.module.ts
|-- app-routing.module.ts
|-- [+] cities
|-- cities.component.html
|-- cities.component.scss
|-- cities.component.spec.ts
|-- cities.component.ts
|-- [+] denver
|-- denver.component.html
|-- denver.component.scss
|-- denver.component.spec.ts
|-- denver.component.ts
I then declared it in app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { FontAwesomeModule } from '#fortawesome/angular-fontawesome';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { CitiesComponent } from './cities/cities.component';
import { DenverComponent } from './cities/denver/denver.component';
#NgModule({
declarations: [
AppComponent,
DashboardComponent,
CitiesComponent,
DenverComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
FontAwesomeModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and then in app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { CitiesComponent } from './cities/cities.component';
import { DenverComponent } from './cities/denver/denver.component';
const routes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'cities', component: CitiesComponent },
{ path: 'cities/denver', component: DenverComponent },
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
I can get to the page fine using a routerLink, but when I type it into the browser or reload it I get a 404 error saying that runtime.js, polyfill.js, etc cannot be found.
Error message
Now that I'm thinking about it, maybe cities needs to be a module? Any help is appreciated, thanks.
Issue sounds like it's related to how you're serving your application and not related to component folder nesting/structure.
You always need to serve index.html page with Angular routing otherwise you will be trying to pull in the server resource absolutely and not letting Angular routing take over.
Your first example with routerlink probably works because you've started the app with http://localhost:4200 and then clicked on link from there and thus not causing a server reload so you will still be within the Angular client side environment.
For example if you're serving your app via Web API you would do something like below to always force index.html to be served on a server request without changing your URL.
.
.
.
builder.Use((context, next) =>
{
context.Request.Path = new PathString("/index.html");
return next();
});
.
.
.
Routed apps must fallback to index.html:
https://angular.io/guide/deployment#fallback
I'm using apollo client for graphql. I set up the client in AppApolloModule that I'm importing in AppModule. I'm making a query in a service which is also imported right in the AppModule. Although the service runs before the AppApolloModule runs and hence apollo is not initialized when the query is made and I get this error
Error: Client has not been defined yet
AppApolloModule
imports ....
export class AppApolloModule {
constructor(
apollo: Apollo,
httpLink: HttpLink,
private userService: UserService
) {
console.log("apollo module")
apollo.create({
link: httpLink.create({ uri: `${environment.apiBase}/graphql?${this.myService.token}`}),
cache: new InMemoryCache()
})
}
}
App Module
import { AppApolloModule } from './app.apollo.module';
import { MyService } from './services/my.service';
export class AppModule {
constructor() {
console.log("app module")
}
}
I don't get the two consoles app module and apollo module, since the service runs first, it doesn't find any initialized apollo app and thus breaks the code.
How can I make apollo run before the service or any services for that matter in an efficient and standard way?
This will solve the issue nicely:
import {NgModule} from '#angular/core';
import {HttpClientModule} from '#angular/common/http';
import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';
import {HttpLink, HttpLinkModule} from 'apollo-angular-link-http';
import {InMemoryCache} from 'apollo-cache-inmemory';
export function createApollo(httpLink: HttpLink) {
return {
link: httpLink.create({uri: 'https://api.example.com/graphql'}),
cache: new InMemoryCache(),
};
}
#NgModule({
imports: [HttpClientModule, ApolloModule, HttpLinkModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
class AppModule {}
The answer by #wendellmva didn't work for me. What did work was the solution suggested in this repo:
https://github.com/patricknazar/angular-lazy-loading-apollo-client
which is basically to put Apollo initialization in a separate, shared module, and include it in your main app module with forRoot().
I have the same issue an the docs from Apollo helped me. Go to 'https://www.apollographql.com/docs/angular/basics/setup/' or copy this:
import { HttpClientModule } from "#angular/common/http";
import { ApolloModule, APOLLO_OPTIONS } from "apollo-angular";
import { HttpLinkModule, HttpLink } from "apollo-angular-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
#NgModule({
imports: [
BrowserModule,
HttpClientModule,
ApolloModule,
HttpLinkModule
],
providers: [{
provide: APOLLO_OPTIONS,
useFactory: (httpLink: HttpLink) => {
return {
cache: new InMemoryCache(),
link: httpLink.create({
uri: "https://o5x5jzoo7z.sse.codesandbox.io/graphql"
})
}
},
deps: [HttpLink]
}],
})
export class AppModule {}
What worked for me was deleting the .angular folder and serving the application again.
I've got this routing file:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomepageComponent } from './app/homepage/homepage.component';
import { SearchpageComponent } from './app/searchpage/searchpage.component';
import { EventPageComponent } from './app/eventpage/eventpage.component';
const routes: Routes = [
{
path: '',
component: HomepageComponent
},
{
path: 'search',
component: SearchpageComponent
},
{
path: 'event/:name/:id',
component: EventPageComponent
},
];
#NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Whenever I try to navigate to an URL like http://localhost:4200/event/asa/123, it won't load the EventPageComponent (blank page) and Chrome gives me the following error in console:
Failed to load resource: the server responded with a status of 404 (Not Found) (http://localhost:4200/event/asa/inline.bundle.js)
It does that for every bundle.
Am I missing something?
It looks like your script reference in index.html is incorrect. It appears to be pointing at inline.bundle.js (relative to the current path) when it should be pointing at /inline.bundle.js (absolute). That's my best guess given your problem, I see nothing wrong with the Angular code (nor could anything in Angular produce this error).
If you're using something like webpack for bundling they no doubt have a solution for this.
I am trying to find out the reason for the following error.
app/src/app.module.ts(13,33): error TS2307: Cannot find module 'src/components/test/test.module
I am using Angular2 RC5 and created a feature module and imported it in app.module.ts file. I am using lazy loading of the module with the router.
app.module.ts looks like this
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { routing } from './app.routes';
/* App Root */
import { AppComponent } from './app.component';
/* Feature module */
import { TestModule } from 'src/components/test/test.module';
#NgModule({
imports: [ BrowserModule, routing ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: []
})
export class AppModule { }
test.module.ts looks like this
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { TestComponent } from './test.component';
import { routing } from './test.routes';
#NgModule({
imports: [ CommonModule, routing ],
declarations: [ TestComponent ],
providers: []
})
export default class TestModule { }
app.routes.ts looks like
import { Routes, RouterModule } from '#angular/router';
export const routes: Routes = [
{
path: '',
redirectTo: '/test',
pathMatch: 'full'
},
{
path: 'test',
loadChildren: 'src/components/test/test.module'
}
];
export const routing = RouterModule.forRoot(routes);
test.routes.ts looks like
import { Routes, RouterModule } from '#angular/router';
import { TestComponent } from './test.component';
const routes: Routes = [
{ path: '',
component: TestComponent }
];
export const routing = RouterModule.forChild(routes);
Above error appears when I try to compile test.module.ts file with default keyword. If I remove it, error disappears. but of course, in that case, I won't be able to use lazy loading for feature module.
Does anyone come across this?
I see multiple errors in your code.
You are importing wrong module in your AppModule.
Your export class name of test.module.ts is TestModule, but you are importing DashboardModule in your AppModule.
Instead of:
import { DashboardModule } from 'src/components/test/test.module';
You should import:
import { TestModule } from 'src/components/test/test.module';
And, of course, you need to add TestModule to your AppModule imports.