I've set up routing in angular that works perfectly correct within application, however if I navigate to my about page for example so http://localhost:9000/about and refresh the page I get error saying "Cannot GET /about", same happens if I open a new tab and paste url there and visit the page.
My boot.ts file containint routing logic
// -- Typescript typings -------------------------------------------------------
/// <reference path="../typings/jquery.d.ts" />
/// <reference path="../typings/jqueryui.d.ts" />
//Imports ----------------------------------------------------------------------
import {Component, enableProdMode} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {
ROUTER_DIRECTIVES,
ROUTER_PROVIDERS,
Router,
RouteConfig,
} from 'angular2/router';
// -- Application Imports ------------------------------------------------------
import {NavbarComponent} from './components/navbar.component';
import {HomePage} from './pages/home.page';
// -- Enable production module -------------------------------------------------
enableProdMode();
// -- Component ----------------------------------------------------------------
#Component({
selector: 'main-app',
directives: [ ROUTER_DIRECTIVES, NavbarComponent ],
template: `
<app-navbar></app-navbar>
<router-outlet></router-outlet>
`
})
// -- Routing ------------------------------------------------------------------
#RouteConfig([
{ path: '/', name: 'root', redirectTo: ['/Home'] },
{ path: '/home', name: 'Home', component: HomePage }
])
// -- Class --------------------------------------------------------------------
export class MainApp {
constructor(public router: Router) {}
}
// -- Bootstrap for application ------------------------------------------------
bootstrap(MainApp, [
ROUTER_PROVIDERS
]);
the index.html file
<!doctype html>
<html lang="en">
<head>
<base href="/">
<meta charset="UTF-8">
<title>Angular2 starter</title>
<!-- Application css -->
<link href="dist/libraries/bundle.css" rel="stylesheet"></link>
<link href="dist/styles/main.css" rel="stylesheet"></link>
</head>
<body>
<main-app>Loading...</main-app>
<!-- Application js -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="dist/libraries/bundle.js"></script>
</body>
<!-- ES6-related imports -->
<script src="/node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="/node_modules/es6-shim/es6-shim.min.js"></script>
<script src="/node_modules/systemjs/dist/system.js"></script>
<script>
//configure system loader
System.config({defaultJSExtensions: true});
</script>
<script src="/node_modules/rxjs/bundles/Rx.js"></script>
<script src="/node_modules/angular2/bundles/angular2.min.js"></script>
<script>
//bootstrap the Angular2 application
System.import('dist/app/boot').catch(console.log.bind(console));
</script>
</html>
and project structure
dist/
app/
components/
navbar.component.js
pages/
home.page.js
boot.js
assets/
typings/
src/
... original files that are compiled into dist here
index.html
In your boot.ts, put this:
import { bootstrap } from "angular2/platform/browser";
import { bind } from "angular2/core";
import { ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy } from "angular2/router";
bootstrap(MainApp, [
ROUTER_PROVIDERS,
bind(LocationStrategy).toClass(HashLocationStrategy)
]);
Your URL's will be with #/home
To complement what Vlado said, with the default strategy you need a server configuration to redirect all your paths to your HTML entry point file. With the hashbang approach it's not necessary...
You could have a look at these questions about this issue:
When I refresh my website I get a 404. This is with Angular2 and firebase
PathLocationStrategy vs HashLocationStrategy in web apps
Is Angular 2's Router broken when using HTML5 routes?
Hope it helps you,
Thierry
enable hashes with your routes
export const routing = RouterModule.forRoot(appRoutes, { useHash: true });
Related
After installing fresh installation of Laravel i installed VueRouter and after implementing simple code for that such as below, i can't use VueJs and i don't get any error in terminal:
commands don't show any error and i get build successful from Laravel mix
/resources/js/app.js content:
GITHUB project link:
import Vue from "vue";
import VueRouter from 'vue-router';
import ExampleComponent from "./components/ExampleComponent";
require('./bootstrap');
const routes = new VueRouter(
{
mode:'history',
routes:[
{
path:'/',
component:ExampleComponent
}
]
}
);
const app = new Vue({
el: '#app',
routes
});
/resources/js/bootstrap.js content:
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
app.blade.php content:
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
#yield('content')
</div>
</body>
</html>
welcome.blade.php content:
#extends('layouts.app')
#section('content')
<div class="container">
<router-view></router-view>
</div>
#endsection
laravel web.php content:
Route::get('/{any}', function () {
return view('welcome');
})->where('any','.*');
simple piece of laravel composer.json:
"require": {
"php": "^7.3|^8.0",
"fideloper/proxy": "^4.4",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.12",
"laravel/tinker": "^2.5",
"laravel/ui": "^3.2"
},
webpack.mix.js content:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.vue()
.sass('resources/sass/app.scss', 'public/css');
and then:
php artisan serve && npm run watch
i have empty page after navigating to / in browser http://127.0.0.1:8000
how can i resolve this issue to use vuejs?
Concerning Vue router, what I usually have is a separated router.js file because it can be lengthy:
import Vue from 'vue'
import Router from 'vue-router'
...
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/users',
name: 'users',
component: () => import('./views/users/_users.vue'),
}
...
]
export default router
And in main.js I have:
import router from './router' // path to router.js file
...
Vue.router = router
...
export default new Vue({
store,
router,
render: h => h(App)
}).$mount('#app')
These constraints are appearently superfluous: ->where('any','.*').
And the route might not match - or .htaccess might be absent;eg. to capture regex (.*) into variable $page for any method:
Route::any('(.*)', function($page) {
// dd($page);
return view('welcome');
});
Not sure, but you probably also need to Vue.use(VueRouter); the docs also initialize differently:
const app = new Vue({routes}).$mount('#app')
I mean, there is no debug information and there are even two ways how to install VueRouter.
In dev mode everything works fine but after building with static it's just blank page! I've seen a lot of issues but no one is similar to mine.
router/index.js:
import Vue from 'vue'
import Router from 'vue-router'
import Main from '#/components/Main'
import BrandPage from '#/components/BrandPage'
import Article from '#/components/Article'
Vue.use(Router)
console.log("Router");
export default new Router({
mode: 'history',
routes: [
{
path: '/',
component: Main,
props: dynamicPropsMain
}
...
]
})
main.js:
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false;
console.log("main");
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
App.vue:
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
mounted() {
console.log("App");
}
}
</script>
<style>
</style>
Also I'm logging every component this way:
mounted() {
console.log("Main");
}
And this is what I see in console when I open the index.html file from dist folder:
There's no an error btw!
I changed all paths to relative in index.html as you can see:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>cosmetic</title>
<link href=./static/css/app.6e402e4fa684582f062c00087423d24c.css rel=stylesheet>
</head>
<body>
<script src=https://use.fontawesome.com/5c25b8d8cc.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js></script>
<div id=app></div>
<script type=text/javascript src=./static/js/manifest.2ae2e69a05c33dfc65f8.js></script>
<script type=text/javascript src=./static/js/vendor.5f799c4e5a271a20f280.js></script>
<script type=text/javascript src=./static/js/app.3990053e5416194b5d89.js></script>
</body>
</html>
These all make me to think that the problem with router and I don't know how to check deeper...
Please anyone help me with that!!! I'll be very grateful!
Are you just trying to open the index.html? This will not work.
In order to use your Vue application, you have to serve the entire dist folder over a Web server.
I am using Chrome browser, Angular 2 with TypeScript. Following is my code;
index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 - Simple Reddit</title>
<script src="node_modules/es6-shim/es6-shim.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<link rel="stylesheet" href="resources/vendor/semantic.min.css" type="text/css">
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<script src="systemjs.config.js"></script>
<script>
System.import('app.js')
.then(console.log('app.js Loaded!!'), console.error.bind(console));
</script>
<app-reddit></app-reddit>
</body>
</html>
app.ts:
import { Component } from "#angular/core";
import { NgModule } from '#angular/core';
#Component({
selector: 'app-reddit',
template: "<div>Reddit Clone! ... </div>"
})
export class AppReddit{}
app.module.ts:
import { NgModule } from '#angular/core';
import { AppReddit } from './app';
#NgModule({
declarations: [AppReddit],
bootstrap: [AppReddit]
})
export class AppRedditModule{};
main.ts:
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppRedditModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppRedditModule);
My code compiles fine with the tsc command. When I run it, I get the app Loaded!! message in console too, but it shows a blank page.
There are no Console errors or warnings.
What am I missing?
Does it show any error in console?
Did you create the project with Angular CLI?
Try to add catch to the main.ts: platformBrowserDynamic().bootstrapModule(AppRedditModule).catch(err => console.log(err));
And try to add <base href="/"> into index.html head tag
Unimportant but I have to say it:
In app.ts you don't need import { NgModule } from '#angular/core'; and if you would need it, you can add it to the first import. But you don't need it.
Please change selector in your component
#Component({
selector: 'app-reddit',
template: "<div>Reddit Clone! ... </div>"
})
You have typo in selector
I want to create simple links to components via Vue-router plugin.
For that I created a routes.js file like this :
import VueRoute from 'vue-router';
let routes = [
{
path: '/',
component: './components/Home'
},
{
path: '/About',
component: './components/About'
}
];
export default new VueRoute({
routes
});
And there is app.js file like this :
import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';
import router from 'routes';
window.Vue = Vue;
window.axios = axios;
Vue.use(VueRouter);
new Vue({
el: '#app',
router
});
And this is my master page content :
<!doctype html>
<html lang="{{ config('app.locale') }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/app.css">
<title>My First Laravel Vue App </title>
</head>
<body>
<div id="app">
<router-link to="/">Home</router-link>
<router-link to="/About">About</router-link>
</div>
<script src="/js/app.js"></script>
</body>
</html>
But After compiling all js files when I open page,router-link does not work and just creates a simple empty html comment instead.
I do not know what is problem and how Can I solve that.
Update:
I changed import router from 'routes'; to import router from './routes' and all things worded fine!
you have everything setup but fforgot the router-view
Add it like this:
<body>
<div id="app">
<router-link to="/">Home</router-link>
<router-link to="/About">About</router-link>
<router-view></router-view>
</div>
<script src="/js/app.js"></script>
</body>
The matched routes are rendered in the router-view
EDIT
The component property of the route object should be the component itself but you are passing it a string
So do it like this:
import VueRoute from 'vue-router';
import Home from './components/Home'
import About from './components/About')
let routes = [
{
path: '/',
component: Home
},
{
path: '/About',
component: About
}
];
export default new VueRoute({
routes
});
This question already has answers here:
Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property
(12 answers)
Closed 6 years ago.
yes, this is probably the hundredth time some one experiences this problem, but no solution worked for me...
I am using angular 2.0.0 rc and nothing will work, I guess I am missing something, but I have no idea what
this are my files, they all transpile correctly, and yes I tried using the not deprecated route, and yes I did it according to the documentation, both don't work.
app.component.ts
import { Component, OnInit } from '#angular/core';
import {Routes, Router, ROUTER_DIRECTIVES} from '#angular/router';
import {LoginComponent} from './login/login.component';
import {HomeComponent} from './home/home.component';
#Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<nav>
<a [routerLink]="['/login']">login</a>
<a [routerLink]="['/home']">home</a>
</nav>
<router-outlet></router-outlet>
`, directives: [ROUTER_DIRECTIVES]
})
#Routes([
{ path: '/login', component: LoginComponent},
{ path: '/home', component: HomeComponent},
])
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['/home']);
}
}
main.ts
import { bootstrap } from '#angular/platform-browser-dynamic';
import { ROUTER_PROVIDERS } from '#angular/router';
import { AppComponent } from './components/app.component';
bootstrap(AppComponent, [ROUTER_PROVIDERS]);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
the rest of the files are pretty much a copy paste from the tutorial, so I won't spam with more code...
Update, I will add that for some reason npm logs don't send a GET request to #angular/routes-deprecated/... but they do send it to other modules.
however it is included in the package.json and systemjs.config.js
I think I know what the problem is, I am not sure what is causing it though
as you see there is no routes folder in the chrome assets. Therefore it makes sense it won't know it - however the node_modules in the project files is there, it is specified in the systemjs.config.js just like any other module...
They have deprecated the RC2 router: http://angularjs.blogspot.com.au/2016/06/improvements-coming-for-routing-in.html
I used the 3.0.0-alpha.7 version.
Based on their example I also made an app.routes.ts file:
import { provideRouter, RouterConfig } from '#angular/router';
import { FooComponent, BarComponent, BazComponent } from './components/bunchOComponents.ts'
export const routes: RouterConfig = [
{ path: 'foo', component: FooComponent },
{ path: 'bar', component: BarComponent },
{ path: 'baz', component: BazComponent }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
I then used this in my main.ts file:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { AppComponent } from './components/appcomponent.ts';
import { APP_ROUTER_PROVIDERS } from './app.routes';
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS
])
.catch(err => console.error(err));
HTH
Since RC.0 angular changed the router to a new implementation, which means that a lot of the examples available online are of the old router.
If you are using #RouteConfig it's the old router.
And it's that one that is available at #angular/router-deprecated
The new router uses #Routes and is available from #angular/router
Otherwise the importing of the ROUTER_DIRECTIVES and ROUTER_PROVIDERS are the same.
Other changes that are significant between the releases are.
the new router doesn't support named routes.
Routes
Before:
import {RouteConfig} from '#angular/router-deprecated';
#RouteConfig([
{path: '/myroute/:id', component: MyRoute, name: 'MyRoute'}
])
After:
import {Routes} from '#angular/router';
#Routes([
{ path: '/myroute/:id`, component: MyRoute }
])
routerLink
The routerLink directive also changed, and doesn't take an object as a second parameter to specify path variables such as id
Before:
<a routerLink="['MyRoute', {id: 1}]">Link</a>
After:
<a routerLink="['/myroute', 1]">Link</a>
Angular needs the [...] around the property name to indicate that it is a binding it needs to resolve. The [...] in the value is only to make Angular parse the assigned value as array.
<a [routerLink]="['/login']">login</a>
<a [routerLink]="['/home']">home</a>
This doesn't explain the error message you get because the error message indicates binding to a property that doesn't exist, while my correction is to make Angular actually do the binding.