Token must be defined! error - angularjs

When my main.ts is to bootstrap app.ts, everything looks good.
main.ts
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from 'app/app';
import {ROUTER_PROVIDERS,ROUTER_DIRECTIVES} from 'angular2/router';
import {PLATFORM_DIRECTIVES,provide} from 'angular2/core';
bootstrap(AppComponent,
[ROUTER_PROVIDERS,
provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi:true}),
]);
app.ts
import {Component,View} from 'angular2/core';
import {RouteConfig} from 'angular2/router';
import {PlayerManagement} from './partials/player-management';
import {Report} from './partials/report';
#Component({
selector: 'my-app',
templateUrl: 'app/appComponent.html',
})
#RouteConfig([
{path:'/playerManagement', name: 'PlayerManagement', component: PlayerManagement},
{path:'/report', name: 'Report', component: Report}
])
export class AppComponent { }
But when I try to change to bootstrap another ts , login.ts, it gives me the error
angular2.js:22823 EXCEPTION: Token must be defined!
execute # main.ts:22
the code line is,
execute: function() {
bootstrap(LoginComponent, [ROUTER_PROVIDERS, provide(PLATFORM_DIRECTIVES, {
useValue: [ROUTER_DIRECTIVES],
multi: true
})]);
}
I compare the login.ts to app.ts , but no clue yet...
login.ts
import {Component,View} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
#Component({
selector: 'login',
templateUrl: 'app/login.html',
})
/*
#RouteConfig([
{path:'/app', name: 'AppComponent', component: AppComponent}
])
*/
export class LoginComponent { }
Updated main.ts
import {bootstrap} from 'angular2/platform/browser';
import {LoginComponent} from 'app/login';
import {ROUTER_PROVIDERS,ROUTER_DIRECTIVES} from 'angular2/router';
import {PLATFORM_DIRECTIVES,provide} from 'angular2/core';
bootstrap(LoginComponent,
[ROUTER_PROVIDERS,
provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi:true}),
]);
index.html
<!doctype html>
<html lang="">
<head>
<base href="/">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>video-platform</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="lib/es6-shim.min.js"></script>
<script src="lib/angular2-polyfills.js"></script>
<script src="lib/traceur-runtime.js"></script>
<script src="lib/system-csp-production.src.js"></script>
<script src="lib/Reflect.js"></script>
<script src="lib/angular2.js"></script>
<script src="lib/Rx.js"></script>
<script src="lib/router.dev.js"></script>
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'ts'
}
}
});
System.import('app/main')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<login>Loading....</login>
<my-app>Loading....</my-app>
</body>
</html>
My folder structure is
src
-app
--app.ts
--appComponent.html
--login.html
--login.ts
--main.ts
Strack trace updated.
STACKTRACE:
BrowserDomAdapter.logError # angular2.js:22823
ExceptionHandler.call # angular2.js:1165
(anonymous function) # angular2.js:12624
run # angular2-polyfills.js:138
(anonymous function) # angular2.js:13328
NgZone.run # angular2.js:13290
ApplicationRef_.bootstrap # angular2.js:12602
bootstrap # angular2.js:24543
execute # main.ts:22
ensureEvaluated # system-csp-production.src.js:2678
execute # system-csp-production.src.js:2796
doDynamicExecute # system-csp-production.src.js:715
link # system-csp-production.src.js:908
doLink # system-csp-production.src.js:569
updateLinkSetOnLoad # system-csp-production.src.js:617
(anonymous function) # system-csp-production.src.js:430
run # angular2-polyfills.js:138
zoneBoundFn # angular2-polyfills.js:111
lib$es6$promise$$internal$$tryCatch # angular2-polyfills.js:1511
lib$es6$promise$$internal$$invokeCallback # angular2-polyfills.js:1523
lib$es6$promise$$internal$$publish # angular2-polyfills.js:1494
(anonymous function) # angular2-polyfills.js:243
run # angular2-polyfills.js:138
zoneBoundFn # angular2-polyfills.js:111
lib$es6$promise$asap$$flush # angular2-polyfills.js:1305
I am using ts, but i have attached the js (main.js) here as well
System.register("app/main", ["angular2/platform/browser", "app/login", "angular2/router", "angular2/core"], function($__export) {
"use strict";
var bootstrap,
LoginComponent,
ROUTER_PROVIDERS,
ROUTER_DIRECTIVES,
PLATFORM_DIRECTIVES,
provide;
return {
setters: [function($__m) {
bootstrap = $__m.bootstrap;
}, function($__m) {
LoginComponent = $__m.LoginComponent;
}, function($__m) {
ROUTER_PROVIDERS = $__m.ROUTER_PROVIDERS;
ROUTER_DIRECTIVES = $__m.ROUTER_DIRECTIVES;
}, function($__m) {
PLATFORM_DIRECTIVES = $__m.PLATFORM_DIRECTIVES;
provide = $__m.provide;
}],
execute: function() {
bootstrap(LoginComponent, [ROUTER_PROVIDERS, provide(PLATFORM_DIRECTIVES, {
useValue: [ROUTER_DIRECTIVES],
multi: true
})]);
}
};
});
package.json
{
"name": "video-platform",
"version": "0.0.0",
"scripts": {
"build": "gulp",
"start": "gulp dev"
},
"dependencies": {
"angular2": "2.0.0-beta.2",
"traceur": "0.0.102",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"rxjs": "5.0.0-beta.0",
"zone.js": "0.5.10",
"reflect-metadata": "0.1.2",
"systemjs": "0.19.6"
},
"devDependencies": {
"gulp": "3.9.0",
"gulp-rename": "1.2.2",
"gulp-traceur": "0.17.2",
"gulp-webserver": "0.9.1",
"gulp-print":"*"
}
}
gulpfile.js
var gulp = require('gulp'),
rename = require('gulp-rename'),
traceur = require('gulp-traceur'),
webserver = require('gulp-webserver');
// run init tasks
gulp.task('default', ['dependencies', 'ts','html', 'css']);
// run development task
gulp.task('dev', ['watch', 'serve']);
// serve the build dir
gulp.task('serve', function () {
gulp.src('build')
.pipe(webserver({
open: true
}));
});
// watch for changes and run the relevant task
gulp.task('watch', function () {
//gulp.watch('src/**/*.js', ['js']);
gulp.watch('src/**/*.ts', ['ts']);
gulp.watch('src/**/*.html', ['html']);
gulp.watch('src/**/*.css', ['css']);
});
// move dependencies into build dir
gulp.task('dependencies', function () {
return gulp.src([
'node_modules/traceur/bin/traceur-runtime.js',
'node_modules/systemjs/dist/system-csp-production.src.js',
'node_modules/systemjs/dist/system.js',
'node_modules/reflect-metadata/Reflect.js',
'node_modules/angular2/bundles/angular2.js',
'node_modules/angular2/bundles/angular2-polyfills.js',
'node_modules/rxjs/bundles/Rx.js',
'node_modules/es6-shim/es6-shim.min.js',
'node_modules/es6-shim/es6-shim.map',
'node_modules/angular2/bundles/angular2.dev.js',
'node_modules/angular2/bundles/router.dev.js'
])
.pipe(gulp.dest('build/lib'));
});
// transpile & move js
gulp.task('js', function () {
return gulp.src('src/**/*.js')
.pipe(rename({
extname: ''
}))
.pipe(traceur({
modules: 'instantiate',
moduleName: true,
annotations: true,
types: true,
memberVariables: true
}))
.pipe(rename({
extname: '.js'
}))
.pipe(gulp.dest('build'));
});
// transpile & move ts
gulp.task('ts', function () {
return gulp.src('src/**/*.ts')
.pipe(rename({
extname: ''
}))
.pipe(traceur({
modules: 'instantiate',
moduleName: true,
annotations: true,
types: true,
memberVariables: true
}))
.pipe(rename({
extname: '.ts'
}))
.pipe(gulp.dest('build'));
});
// move html
gulp.task('html', function () {
return gulp.src('src/**/*.html')
.pipe(gulp.dest('build'))
});
// move css
gulp.task('css', function () {
return gulp.src('src/**/*.css')
.pipe(gulp.dest('build'))
});

Related

Buffer is not defined in React-vite

Buffer is not defined after migrating from CRA(create react app)
"vite": "^2.7.12"
I try to add plugins, add define for Buffer, but it's not work.
const viteConfig = defineConfig({
/* define: {
"Buffer": {}
},*/
plugins: [reactRefresh(), react()],
build: {
rollupOptions: {
input: {
main: resolve('index.html'),
},
},
},
clearScreen: false
});
Install this library
#esbuild-plugins/node-globals-polyfill
and add this in your vite.config.js
export default defineConfig({
// ...other config settings
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
buffer: true
})
]
}
}
})
add this libary import to your vite.config.js
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
Николай Сычев solution didn't work for me at first.
Instead, I succeeded by simply
installing buffer as a dev dependency
yarn add buffer (use npm equivalent if you use npm)
and then adding it to the global scope in the index.html like this:
<html lang="en">
<head>
<script type="module">
import { Buffer } from "buffer";
window.Buffer = Buffer;
</script>
...
It also works for similar dependencies like process which you'd import in the index.html like this:
import process from "process";
window.process = process;
Update
For a different project I needed util, which required process. The above suggested method didn't suffice in that case.
Instead I found out that #esbuild-plugins (for vite dev) and rollup-plugin-polyfill-node (for vite build) would successfully provide all these nodejs packages.
Here is a full vite.config.ts that works for me:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill'
import rollupNodePolyFill from 'rollup-plugin-polyfill-node'
export default defineConfig({
plugins: [vue()],
base: '',
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
buffer: true,
process: true,
}),
NodeModulesPolyfillPlugin()
]
}
},
build: {
rollupOptions: {
plugins: [
rollupNodePolyFill()
]
}
}
})
Be careful to use rollup-plugin-polyfill-node which is an updated and maintained fork of rollup-plugin-node-polyfills.
For me the above configuration did not work, I had to make changes in 3 files ,
in vite.config.ts , index.html and adding packages
1.Install Packages
yarn install process util buffer events
yarn add #esbuild-plugins/node-modules-polyfill
2.Update vite.config
import GlobalPolyFill from "#esbuild-plugins/node-globals-polyfill";
import react from "#vitejs/plugin-react";
import { resolve } from "path";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react()],
optimizeDeps: {
esbuildOptions: {
define: {
global: "globalThis",
},
plugins: [
GlobalPolyFill({
process: true,
buffer: true,
}),
],
},
},
resolve: {
alias: {
process: "process/browser",
stream: "stream-browserify",
zlib: "browserify-zlib",
util: "util",
},
},
});
3.Update index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/assets/images/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<script>
window.global = window;
</script>
<script type="module">
import process from "process";
import EventEmitter from "events";
import {Buffer} from "buffer";
window.Buffer = Buffer;
window.process = process;
window.EventEmitter = EventEmitter;
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.js"></script>
</body>
</html>
Another approach is:
npm i -D rollup-plugin-polyfill-node
Then update vite.config.ts with the following:
import nodePolyfills from 'rollup-plugin-polyfill-node'
rollupOptions: {
plugins: [
// ...plugins
nodePolyfills(),
],
// ...rollupOptions
},

AngularJS + Angular 8 not working together [ Hybrid application ]

I have a use case to migrate a large angularjs application and I want to start by doing this process in a small application first. So for that reason, I've took the tour of heroes angularjs webapp and I started to add angular to it ( by creating a new project with the angular-cli ) and then adding the NgUpgrade module.
The problem that I have now is that the angularjs webapp runs pretty well inside the angular 8 application but the components that belong to angular 8 they are not rendered.
I have the impression that my angular components are not bootstrapped since I've bootsraped manually angularjs but I'm not sure ... when I add explicitly the bootstrap property inside the #NgModules it works only for the angular components but not for angularjs (it makes sense ). So I was thinking maybe I have to upgrade the angularjs components or downgrade the newest angular components but I don't think so.
Here you will find the git repository with the code. Below more information related to my project:
angular version: 8.2.8
angularJS version: 1.6.10
angular-cli: 8.3.6
Project structure
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Common</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<hero-list></hero-list>
</body>
</html>
index.ts ( angularjs root module)
// initialize root module and make it exportable to be able to bootstrap it
// inside angular
export const heroAppModule = angular.module('heroApp', [
'ngMaterial',
'perfect_scrollbar',
'ngJsTree',
'ngTagsInput',
'ui.router',
'heroApp.underscore'
]).config(['$stateProvider', function ($stateProvider) {
var heroState = {
name: 'hero',
url: '/hero',
template: '<hero-list></hero-list>'
};
$stateProvider.state(heroState);
}]);
/** start: REQUIRE ZONE for angularjs
* Add angularjs files since they aren't yet fully ES6 modules
* we use requirejs as module loader
*/
require('./editable-field/editable-field');
require('./hero-detail/hero-detail');
require('./hero-list/hero-list');
require('./underscore/underscore.module');
require('./underscore/underscore.service');
/**
* end: REQUIRE ZONE for angularjs
*/
app.module.ts ( bootstraping angularjs with NgUpgrade )
import * as angular from 'angular';
import { UpgradeModule, setAngularJSGlobal } from '#angular/upgrade/static';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { heroAppModule } from './../ngjs/index';
import { HelloworldComponent } from './helloworld/helloworld.component';
#NgModule({
declarations: [ HelloworldComponent ],
imports: [
BrowserModule,
UpgradeModule
] // ,
// bootstrap: [HelloworldComponent]
})
export class AppModule {
constructor(private upgrade: UpgradeModule) { }
ngDoBootstrap() {
setAngularJSGlobal(angular);
this.upgrade.bootstrap(document.body, [heroAppModule.name], { strictDi: true });
}
}
main.ts
import 'zone.js/dist/zone'; // Included with Angular CLI.
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/ngx/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
hero list component (angularjs)
declare var angular: angular.IAngularStatic;
(function () {
'use strict';
angular.module('heroApp').component('heroList', {
template: require('html-loader!./hero-list.html'),
controller: HeroListController,
controllerAs: 'vm'
});
HeroListController.$inject = ['$scope', '$element', '$attrs'];
function HeroListController($scope, $element, $attrs) {
var vm = this;
vm.list = [
{
name: 'Superman',
location: 'The sky'
},
{
name: 'Batman',
location: 'Baticueva'
}
];
vm.updateHero = function (hero, prop, value) {
hero[prop] = value;
};
vm.deleteHero = function (hero) {
var idx = vm.list.indexOf(hero);
if (idx >= 0) {
vm.list.splice(idx, 1);
}
};
}
})();
app-root component ( file name: helloworld.component)
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './helloworld.component.html',
styleUrls: ['./helloworld.component.scss']
})
export class HelloworldComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
app-root template
<p>helloworld works!</p>
angular.json ( angular-cli file )
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"common": {
"projectType": "application",
"schematics": {
"#schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/common",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets" ],
"styles": [
"bower_components/jstree/dist/themes/default/style.min.css",
"bower_components/ng-tags-input/ng-tags-input.bootstrap.min.css",
"bower_components/utatti-perfect-scrollbar/css/perfect-scrollbar.css",
"bower_components/angular-material/angular-material.css",
"src/styles.scss"
],
"scripts": [
"bower_components/jquery/dist/jquery.js",
"bower_components/angular/angular.js",
"bower_components/angular-material/angular-material.js",
"bower_components/angular-animate/angular-animate.js",
"bower_components/angular-aria/angular-aria.js",
"bower_components/jstree/dist/jstree.js",
"bower_components/ng-js-tree/dist/ngJsTree.js",
"bower_components/ng-tags-input/ng-tags-input.js",
"bower_components/utatti-perfect-scrollbar/dist/perfect-scrollbar.js",
"bower_components/angular-perfect-scrollbar/src/angular-perfect-scrollbar.js",
"node_modules/#uirouter/angularjs/release/angular-ui-router.min.js",
"node_modules/underscore/underscore.js"
]
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "common:build"
},
"configurations": {
"production": {
"browserTarget": "common:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "common:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "common:serve"
},
"configurations": {
"production": {
"devServerTarget": "common:serve:production"
}
}
}
}
}},
"defaultProject": "common"
}
Result...
Finally I've figured out that the solution that I need will never use both components of each framework side by side at the root of my application. Instead, I've used the following pattern as the angular documentation says:
Once you're running a hybrid app, you can start the gradual process of upgrading code. One of the more common patterns for doing that is to use an Angular component in an AngularJS context. This could be a completely new component or one that was previously AngularJS but has been rewritten for Angular.
So as my old application is written in angularjs this framework will contain always my root application and also will be the wrapper of all my future features. So If someday I decide to write a new component in Angular 8 this component will live inside angularjs and it will be downgraded to be able to make it work.
Isolate your Angular 1 code and Angular 8 code
<body>
<app-root></app-root>
<div ng-controller="MyController">
<hero-list></hero-list>
</div>
</body>
I had a similar issue, even though in my index.html I had this:
<body>
<app-root></app-root>
</body>
I found that with the setup of the Angular docs for ngUpgrade, the top-level component needs to be the one from Angular.js, not the one from Angular:
<body>
<hero-list></hero-list>
</body>

Component does not displays in UI page

I started learning Angular2 and tried the "Hello world" program. I have created a .ts file like this:
appComponent.ts
import {
NgModule,
Component
} from '#angular/core';
import {BrowserModule} from '#angular/platform-browser';
import {platfromBrowserDynamic} from '#angular/platfrom-browser-dynamic';
#Component({
selector:'hello-world',
template:`
<div>
Hello world
</div>`
})
class HelloWorld {
}
#NgModule({
declaration: [HelloWorld],
imports:[BrowserModule],
bootStrap:[HelloWorld],
})
class HelloWorldAppModuel{
}
platformBrowserDynamic().bootstrapModule(HelloWorldAppModuel);
But when I deployed and ran this code in Tomcat, it didn't show anything, but it should show "Hello World". I am not able to get why nothing appeared in the UI.
/* Importing Component decorator function from anularjs library module */
System.register(['#angular/core', '#angular/platform-browser'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1, platform_browser_1;
var HelloWorld, HelloWorldAppModuel;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
},
function (platform_browser_1_1) {
platform_browser_1 = platform_browser_1_1;
}],
execute: function() {
HelloWorld = (function () {
function HelloWorld() {
}
HelloWorld = __decorate([
core_1.Component({
selector: 'hello-world',
template: "\n<div>\nHello world\n</div>\n"
}),
__metadata('design:paramtypes', [])
], HelloWorld);
return HelloWorld;
}());
HelloWorldAppModuel = (function () {
function HelloWorldAppModuel() {
}
HelloWorldAppModuel = __decorate([
core_1.NgModule({
declaration: [HelloWorld],
imports: [platform_browser_1.BrowserModule],
bootStrap: [HelloWorld],
}),
__metadata('design:paramtypes', [])
], HelloWorldAppModuel);
return HelloWorldAppModuel;
}());
platformBrowserDynamic().bootstrapModule(HelloWorldAppModuel);
}
}
});
//# sourceMappingURL=appComponent.js.map
<html>
<head>
<title>Angular -2
</title>
<script src="../node_modules/core-js/client/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>
</head>
<body>
<script src="../systemjs.config.js"></script>
<script>
System.import('appComponent.js')
.then(null,console.error.bind(consol));
</script>
<hello-world></hello-world>
</body>
</html>
main.ts file
import {bootStrap} from 'angular2/platform/browser'
import {AppComponent} from './appComponent'
bootstrap(AppComponent);
PFB my snippet. What's going on?
Edit 1:
I checked this thing in chrome is shwos in console like this
Uncaught ReferenceError: consol is not defined(…)(anonymous function) # (index):15
system.src.js:1154 GET http://localhost:8080/angularAssign/#angular/core 404 (Not Found)fetchTextFromURL # system.src.js:1154(anonymous function) # system.src.js:1710ZoneAwarePromise # zone.js:563(anonymous function) # system.src.js:1709(anonymous function) # system.src.js:2734(anonymous function) # system.src.js:3308(anonymous function) # system.src.js:3575(anonymous function) # system.src.js:3960(anonymous function) # system.src.js:4419(anonymous function) # system.src.js:4671(anonymous function) # system.src.js:406ZoneDelegate.invoke # zone.js:306Zone.run # zone.js:201(anonymous function) # zone.js:550ZoneDelegate.invokeTask # zone.js:339Zone.runTask # zone.js:237drainMicroTaskQueue # zone.js:456ZoneTask.invoke # zone.js:408
zone.js:443 Unhandled Promise rejection: Error: XHR error (404 Not Found) loading http://localhost:8080/angularAssign/#angular/core
at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:8080/node_modules/zone.js/dist/zone.js:745:30)
at ZoneDelegate.invokeTask (http://localhost:8080/node_modules/zone.js/dist/zone.js:339:38)
at Zone.runTask (http://localhost:8080/node_modules/zone.js/dist/zone.js:237:48)
at XMLHttpRequest.ZoneTask.invoke (http://localhost:8080/node_modules/zone.js/dist/zone.js:405:34)
Error loading http://localhost:8080/angularAssign/#angular/core as "#angular/core" from http://localhost:8080/angularAssign/appComponent.js ; Zone: <root> ; Task: Promise.then ; Value: Error: Error: XHR error (404 Not Found) loading http://localhost:8080/angularAssign/#angular/core(…)consoleError # zone.js:443drainMicroTaskQueue # zone.js:472ZoneTask.invoke # zone.js:408
zone.js:445 Error: Uncaught (in promise): Error: Error: XHR error (404 Not Found) loading http://localhost:8080/angularAssign/#angular/core(…)consoleError # zone.js:445drainMicroTaskQueue # zone.js:472ZoneTask.invoke # zone.js:408
system.src.js:1154 GET http://localhost:8080/angularAssign/#angular/platform-browser 404 (Not Found)
Edit 2:
here's my systemjs.config.js file:
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
'#angular/upgrade': 'npm:#angular/upgrade/bundles/upgrade.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
Edit 3:
after editing my package.json file like this
{
"name": "angularjs2-app",
"version": "1.0.0",
"scripts": {
"start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.14",
"#angular/common": "~2.1.1",
"#angular/compiler": "~2.1.1",
"#angular/core": "~2.1.1",
"#angular/forms": "~2.1.1",
"#angular/http": "~2.1.1",
"#angular/platform-browser": "~2.1.1",
"#angular/platform-browser-dynamic": "~2.1.1",
"#angular/router": "~3.1.1",
"#angular/upgrade": "~2.1.1",
"angular-in-memory-web-api": "~0.1.5",
"core-js": "^2.4.1",
"systemjs": "0.19.25",
"es6-shim": "^0.35.0",
"es6-promise": "^3.0.2",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.6.6"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.2.0",
"typescript": "^1.8.9",
"typings":"^0.7.12"
}
}
most of the error has gone but still one error is persisted that is
zone.js:306 Error: ReferenceError: platformBrowserDynamic is not defined
at execute (http://localhost:3000/angularAssign/appComponent.js:50:13)
at ZoneDelegate.invoke (http://localhost:3000/node_modules/zone.js/dist/zone.js:306:29)
at Zone.run (http://localhost:3000/node_modules/zone.js/dist/zone.js:201:44)
Error loading http://localhost:3000/angularAssign/appComponent.js
Please let me still what is remaining to add?
Here is a working example and a few things to whatch for when creating new components,
Anytime you create a component you must add it to the
app.module.ts
Example
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HelloComponent } from './hello.component';
#NgModule({
declarations: [ HelloComponent ],
imports: [
HelloComponent,
],
bootstrap: [AppComponent]
})
export class AppModule {
}
Then create a route,
app.routing.ts
import { Routes, RouterModule } from "#angular/router";
import { HelloComponent } from './hello.component';
const APP_ROUTES: Routes = [
{ path: '', component: HelloComponent }
];
export const routing = RouterModule.forRoot(APP_ROUTES);
Then you will have two component files,
Once which is the
hello.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
templateUrl: './hello.component.html',
})
export class HelloComponent {
constructor() { }
}
And as you can see instead ot using template and injecting the html I specify a template. Now it will load the html file I specify. So your last file is,
hello.component.html
Make sure you have all this together and it will run. Then every time you want to add a new component or view follow these steps.

(systemjs) xhr error (404 not found) loading

I use a service in an Angular 2 app, and I get an error which is attached below.
I started this project using "Angular 2 QuickStart" cloned as 'my-proj'.
Error screenshot
systemjs.config.js
/**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
'#angular/upgrade': 'npm:#angular/upgrade/bundles/upgrade.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule, JsonpModule } from '#angular/http';
import { AppComponent } from './app.component';
import { ProfileComponent } from './components/profile.component';
#NgModule({
imports: [ BrowserModule,HttpModule,JsonpModule ],
declarations: [ AppComponent,ProfileComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
profile.component.ts
import { Component } from '#angular/core';
import {GithubService} from '../services/github.service';
import 'rxjs/add/operator/map';
#Component({
moduleId:module.id,
selector: 'profile',
templateUrl:'profile.component.html'
})
export class ProfileComponent {
constructor(private githubService:GithubService){
this.githubService.getUser().subscribe(user => {
console.log(user);
});
}
}
github.service.ts
import { Injectable } from '#angular/core';
import {Http,Headers} from '#angular/Http';
import 'rxjs/add/operator/map';
#Injectable()
export class GithubService{
private username:string;
constructor(private http:Http){
console.log('Github Service Ready...');
this.username='bradtraversy';
}
getUser(){
return this.http.get('http://api.github.com/users'+this.username).map(res => res.json);
}
}
In github.service.ts, change
import {Http,Headers} from '#angular/Http'
to
import {Http,Headers} from '#angular/http'
might help.

Error: XHR error (404 Not Found) loading http://localhost:3622/app.js(…) + angular 2

I am trying to build an angular 2 application using typescript in visual studio 2015 application. I am using angular release candidate 1.
I am getting the following error message in the console of my browser while running the application.
index.html:24 Error: Error: XHR error (404 Not Found) loading http://localhost:3622/app.js(…)
I cannot understand why it is trying to look for app.js file. I have set index.html as the start page.
As seen in the code below , I am trying to display data in the datatable. Is there any issue with how I have setup the systemjs.js file or with the system.import statement in index.html file
Please find my folder structure
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/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>
<script src="node_modules/primeui/primeui-ng-all.min.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function (err) { console.error(err); });
</script>
</head>
<body>
<my-app>Loading..</my-app>
</body>
</html>
Systemjs.config.js
(function (global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'#angular': 'node_modules/#angular',
'primeng': 'node_modules/primeng'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'.': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};
var packageNames = [
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/testing',
'#angular/upgrade',
'#angular/router-deprecated'
];
// add package entries for angular packages in the form '#angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function (pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
map: map,
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);
main.ts
import { bootstrap } from '#angular/platform-browser-dynamic';
// Our main component
import { AppComponent } from './app/app.component';
bootstrap(AppComponent, []).catch(err => console.error(err));
app.component.ts
import { Component } from '#angular/core';
import { RiskListComponent } from './components/risks/risk-list.component';
import { DataTable, Column } from 'primeng/primeng';
#Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h1>{{pageTitle}}</h1>
<rm-risks> </rm-risks>
</div>
` ,
directives: [RiskListComponent, DataTable, Column]
})
export class AppComponent {
pageTitle: string = 'Test UK Trader';
}
risk-list.component.ts
import { Component } from '#angular/core'
import { DataTable, Column } from 'primeng/primeng';
#Component({
selector: 'rm-risks',
directives: [DataTable, Column],
templateUrl: '/app/risks/risk-list.component.html'
})
export class RiskListComponent {
pageTitle: string = 'Risk List';
risks: any[] = [
{
"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": "HISC9308340",
"insuredName": "Upper Loi",
"inceptionDate": "April 25, 2016",
"riskType": "Quote",
"status": "Indication",
"grossPremium": "312.22",
"allocatedTo": "Andy Marples",
"allocatedCompany": "Broker"
}
];
}
risk-list.component.html
<h3 class="first">{{pageTitle}}</h3>
<p-dataTable [value]="risks" [rows]="10" [paginator]="true" [pageLinks]="3" [rowsPerPageOptions]="[5,10,20]">
<p-column field="reference" header="Reference"></p-column>
<p-column field="insuredName" header="Insured Name"></p-column>
<p-column field="inceptionDate" header="Inception Date"></p-column>
<p-column field="riskType" header="Risk Type"></p-column>
<p-column field="status" header="Status"></p-column>
<p-column field="grossPremium" header="Gross Premium"></p-column>
<p-column field="allocatedTo" header="Allocated To"></p-column>
<p-column field="allocatedCompany" header="Allocated Company"></p-column>
</p-dataTable>
tsconfig.js
{
"compileOnSave": false,
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": false,
"outDir": "../dist/",
"rootDir": ".",
"sourceMap": true,
"target": "es6",
"inlineSources": true
},
"exclude": [
"node_modules",
"typings",
"typings/main",
"typings/main.d.ts"
]
}
I would move the main.ts file under the app folder and import it this way:
<script>
System.import('app/main').catch(function (err) { console.error(err); });
</script>
You also need to have this configuration for SystemJS:
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};

Resources