Component does not displays in UI page - angularjs

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.

Related

Angular SSR: not rendering pure html page

We are working on a angularJs project where our homepage contains code in which we call some APIs and fill the data accordingly. We need server side rendering and so we followed this tutorial . We ran npm run dev:ssr Everything is working fine however we are not getting fully generated pure html/css page. i can see page hasn't been rendered server side yet. It is still getting rendered in browser side. I don't know what i am doing wrong here. Any help will be appreciated.
Nodejs version : 14.17.2
OS : ubuntu 20.
Here is my package.json file :-
{
"name": "piping-mart-client",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"dev:ssr": "ng run pipingMartClient:serve-ssr",
"serve:ssr": "node dist/pipingMartClient/server/main.js",
"build:ssr": "ng build && ng run pipingMartClient:server",
"prerender": "ng run pipingMartClient:prerender"
},
"private": true,
"dependencies": {
"#angular/animations": "~13.1.0",
"#angular/common": "~13.1.0",
"#angular/compiler": "~13.1.0",
"#angular/core": "~13.1.0",
"#angular/forms": "~13.1.0",
"#angular/localize": "~13.1.0",
"#angular/platform-browser": "~13.1.0",
"#angular/platform-browser-dynamic": "~13.1.0",
"#angular/platform-server": "~13.1.0",
"#angular/router": "~13.1.0",
"#ng-bootstrap/ng-bootstrap": "^12.0.0",
"#ng-select/ng-select": "^8.1.1",
"#nguniversal/express-engine": "^13.0.2",
"#popperjs/core": "^2.10.2",
"angular-material": "^1.2.5",
"angular-ng-autocomplete": "^2.0.8",
"angular-responsive-carousel": "^2.1.2",
"bootstrap": "^5.1.3",
"countrycitystatejson": "^20.8.14",
"ejs": "^3.1.6",
"express": "^4.15.2",
"font-awesome": "^4.7.0",
"intl-tel-input": "^17.0.16",
"jquery": "^3.6.0",
"localstorage-polyfill": "^1.0.1",
"ng2-tel-input": "^2.3.0",
"ngx-owl-carousel-o": "^7.0.2",
"ngx-select-dropdown": "^2.1.0",
"ngx-slick-carousel": "^0.6.0",
"path": "^0.12.7",
"rxjs": "~7.4.0",
"sessionstorage": "^0.1.0",
"slick-carousel": "^1.8.1",
"sweetalert2": "^11.4.9",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"#angular-devkit/build-angular": "^13.2.6",
"#angular/cli": "~13.1.2",
"#angular/compiler-cli": "~13.1.0",
"#nguniversal/builders": "^13.0.2",
"#types/express": "^4.17.0",
"#types/jasmine": "~3.10.0",
"#types/node": "^12.11.1",
"jasmine-core": "~3.10.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.1.0",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.5.2"
}
}
My productcomponent.html page (this is the page which we expect to be rendered. This is the first page which get loaded whenever app is loaded).
<div id="content">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-6 col-sm-12">
<div class="pro-circle p-4">
<img src="{{this.product?.logo || 'https://www.example.com/images/logo.png'}}" class="img-responsive lazyload" alt="Pipes" title="Pipes" />
<h1 class="tab-title">{{this.product.name}}</h1>
</div>
</div>
<div class="col-md-9 col-sm-6 col-sm-12" id="description">
<div id="ProdDesc" class="text show-more-height" [innerHTML]="this.product['description']" >
</div>
<div class="show-more"><button class="btn more">Show More</button></div>
<div class="clearfix"></div>
<div class="container mt-5">
<div class="slide-box mt-5" *ngFor="let slide of material; let i = index;">
<div class="recent-projects">
<a (click)="goToSupplierOfMaterial(slide)" >
<h4 class="title">
<span >{{slide.name}} </span></h4></a>
<div class="projects-carousel touch-carousel">
<owl-carousel-o [options]="customOptions">
<ng-container *ngFor="let gradeList of slide.gradeDetail">
<ng-template carouselSlide [id]="gradeList.gradeId">
<img [src]="gradeList.logo" [alt]="gradeList.alt" [title]="gradeList.name" style="height: 20vh;">
<div class="portfolio-details text-center">
<a class="text-underline cursor-pointer" >
<h4 (click)="goToSupplier(gradeList)">{{gradeList.name}}</h4>
</a>
</div>
</ng-template>
</ng-container>
</owl-carousel-o>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
My product.component.ts page :-
import { HttpClient } from '#angular/common/http';
import { Component, OnInit , PLATFORM_ID , Inject} from '#angular/core';
import { ActivatedRoute , Router} from '#angular/router';
import { OwlOptions } from 'ngx-owl-carousel-o';
import { CookieService } from 'src/app/shared/service/cookie.service';
import { DataService } from 'src/app/shared/service/DataService';
import * as $ from "jquery";
import { isPlatformBrowser , isPlatformServer} from '#angular/common'
#Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.scss']
})
export class ProductComponent implements OnInit {
htmlPage : any;
name : any;
selectedProduct : any [];
arrayOfValues: Array<string>;
productCategory: any;
product: any;
material: any;
materialArray = [];
customOptions: OwlOptions = {
loop: false,
mouseDrag: true,
autoplay: true,
touchDrag: false,
pullDrag: false,
dots: false,
margin: 10,
navSpeed: 700,
navText: ['<i class="fa-solid fa-chevron-left"></i>', '<i class="fa fa-angle-right" aria-hidden="true"></i>'],
responsive: {
0: {
items: 1
},
400: {
items: 4
},
740: {
items: 4
},
940: {
items: 4
}
},
nav: true
}
description: string;
constructor(private activatedRoute : ActivatedRoute ,
private router : Router ,
private _dataService : DataService,
private http : HttpClient ,
private cookieService: CookieService ,
#Inject(PLATFORM_ID) private _platformId: Object) { }
ngOnInit(){
if (isPlatformBrowser(this._platformId)) {
this.activatedRoute.params.subscribe(params => {
this.name = params['name'];
});
this.product = JSON.parse(localStorage.getItem("selectedProduct"));
this.fetchMaterial(this.product['productId'])
}
$(".show-more").click(function () {
if($(".text").hasClass("show-more-height")) {
$(this).text("Show Less...");
} else {
$(this).text("Show More...");
}
$(".text").toggleClass("show-more-height");
});
}
public fetchMaterial(productId){
this.http.post('http://pipe.example.com/product/materials',{"productId" : productId , "includeGrades": true
}).subscribe(
(res : any) => {
this.material = res.data;
},
error => {
console.log(JSON.stringify(error.json()));
}
)
}
public fetchProduct() {
this.http.post('http://pipe.example.com/product/products',{"name" : this.name }).subscribe(
(res : any) => {
//this.productCategory = res.data;
//console.log(res.data);
this.selectedProduct = res.data;
},
error => {
console.log(JSON.stringify(error.json()));
}
)
}
public goToSupplier(grade) {
console.log(grade);
this.router.navigate(['/product/detail/'+ grade.name]);
localStorage.setItem("selectedGrade", JSON.stringify(grade));
}
public goToSupplierOfMaterial(material) {
console.log(material);
this.router.navigate(['/material/'+ material.name]);
localStorage.setItem("selectedMaterial", JSON.stringify(material));
}
}
my server.ts file (got generated after running ng add #nguniversal/express-engine)
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '#nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '#angular/common';
import { existsSync } from 'fs';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const distFolder = join(process.cwd(), 'dist/pipingMartClient/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
// Our Universal express-engine (found # https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
server.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});
return server;
}
function run(): void {
const port = process.env['PORT'] || 4000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export * from './src/main.server';

Angular Hybrid Error: Trying to get the AngularJS injector before it being set

How to use AngularJS service in Angular 5 component?
I have AngularJS application and i am trying to make hybrid app but not able to use AngularJS service insight Angular component : getting error
ERROR Error: Trying to get the AngularJS injector before it being set.
my main.ts is
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
app.module :
import { BrowserModule } from '#angular/platform-browser';
import { NgModule, InjectionToken } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { UpgradeModule, downgradeComponent } from '#angular/upgrade/static';
import { AppComponent } from './app.component';
import { SignInComponent } from "./modules/login/components/sign-in/sign-in.component";
import { authServiceProvider } from './shared/angularJS-upgraded-providers';
#NgModule({
declarations: [
AppComponent,
SignInComponent
],
imports: [
BrowserModule,
UpgradeModule,
FormsModule
],
entryComponents: [
SignInComponent
],
providers: [authServiceProvider],
bootstrap: [SignInComponent]
})
export class AppModule {
ngDoBootstrap() {}
}
angularJS-upgraded-providers.ts :
import { InjectionToken } from "#angular/core";
export const AuthService = new InjectionToken<any>('authService');
export function authServiceFactory(i: any) {
return i.get('authService');
}
export const authServiceProvider = {
provide: AuthService,
useFactory: authServiceFactory,
deps: ['$injector']
};
and sign-in.component.ts :
import { Component, Inject } from '#angular/core';
import {AuthService} from "../../../../shared/angularJS-upgraded-providers";
#Component({
selector: 'sign-in',
template: require('./sign-in.component.html')
})
export class SignInComponent {
constructor(
#Inject(AuthService) private authService: any) {
}
}
When I remove SignInComponent constructor part code compiles well but with #Inject(AuthService) private authService: any) { } part I am getting an error :
Trying to get the AngularJS injector before it being set.
Please give me some suggesting how can I implement angularJS service insight Angular component.
Thanks
P.S. my package.json :
{
"name": "test",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "webpack-dev-server --port=4200 --open chrome"
},
"dependencies": {
"#angular/common": "^5.2.11",
"#angular/compiler": "^5.2.11",
"#angular/core": "^5.2.11",
"#angular/forms": "^5.2.11",
"#angular/http": "^5.2.11",
"#angular/platform-browser": "^5.2.11",
"#angular/platform-browser-dynamic": "^5.2.11",
"#angular/router": "^5.2.11",
"#angular/upgrade": "^5.2.11",
"core-js": "^2.5.7",
"reflect-metadata": "^0.1.12",
"rxjs": "^5.5.11",
"zone.js": "^0.8.26"
},
"devDependencies": {
"#types/jquery": "^3.3.6",
"#types/node": "^8.10.23",
"awesome-typescript-loader": "^5.2.0",
"css-loader": "^1.0.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"raw-loader": "^0.5.1",
"style-loader": "^0.22.1",
"ts-loader": "3.2.0",
"typescript": "^2.9.2",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
And AngularJS version : 1.6.8
This means you are pulling in an AngularJS dependency somewhere in your component tree. It may be in your immediate component or some dependency further down the line.
To debug:
Method 1
Add a debugger statement immediately before your bootstrap call:
it('should render the component', () => {
debugger;
bootstrap(Ng2AppComponent);
...
});
With your JS Console open, let the test run and pause at the debugger location.
Click the Stop/Pause icon (in the sidebar on the 'sources' tab) and checkmark "Pause on Exceptions". Unpause the debugger.
The debugger should stop within a call to injectorFactory. Use the stack explorer to find calls to resolveNgModuleDep. These will be recursive, so the top of the stack will be closer to a leaf node, while calls further down the stack will be closer to your component being tested. Look for lines like: tokenKey = "ServiceName". This is potentially your offending service.
Dive down the stack one more layer to find which component tried to inject that service.
Within your test, mock out a provider to handle that specific injection. Note that this code assumes only one problem injection. For multiple injector issues, you will need to special case these:
beforeEach(() => {
setupModule({
imports: [
...
],
providers: [
{
provide: '$injector',
useValue: {
get: () => {
return new MockService(); // enhance as needed
},
}
}
],
});
Method 2
Mock out a provider for the $injector call, and return an empty object.
beforeEach(() => {
setupModule({
imports: [
...
],
providers: [
{
provide: '$injector',
useValue: {
get: (serviceName?: string) => {
console.log('looking for serviceName:', serviceName);
return {}; // this will break things differently
},
}
}
],
});
Look at your console output to find the offending service / signature. This may or may not involve less work than than Method 1.

Failed to construct 'WebSocket': The URL '[object Object]' is invalid

I was trying to make a connection to the websocket and get the data in react router. The connection is not happening and getting error Uncaught SyntaxError: Failed to construct 'WebSocket': The URL '[object Object]' is invalid. in the browser console. Using npm start from the terminal to start the application. It is a simple react router application. Below is the react code where I think problem occurred.
import React from 'react'
export default React.createClass({
getInitialState: function() {
return { value : [],
client : '' };
},
componentWillMount: function() {
client = new WebSocket("ws://localhost:8000/","echo-protocol");
client.onerror = function() {
console.log('Connection Error');
};
client.onopen = function() {
function sendNumber() {
if (client.readyState === client.OPEN) {
var number = Math.round(Math.random() * 0xFFFFFF);
client.send(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
};
client.onmessage = function(e) {
this.setState({
value: e.data
});
}.bind(this);
},
componentWillUnmount: function(){
client.close();
},
render: function() {
return (React.createElement("div",null,this.state.value))
}
});
The webpack config file is -
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
publicPath: ''
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' }
]
}
}
Also, the packge.json file is
{
"name": "react_form",
"version": "1.0.0",
"description": "Sample form that uses React for its rendering",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --inline --content-base . --history-api-fallback"
},
"author": "J",
"license": "ISC",
"dependencies": {
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0",
"websocket": "^1.0.23"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"http-server": "^0.8.5",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1"
}
}
If any other piece of code is required then please let me know. Also, please find the image of the error coming in the console on selecting the route option. What is the exact issue I am not able to get ?
Try this syntax:
const client = new WebSocket("ws://localhost:8000/");
I was debugging the app in various different ways I could. Then I found that there is no problem with the code. Further changed the name of the file from WebSocket to Socket and route name from webSocket to socket in various files and it worked. The problem was with naming the files and including them into the code accordingly.
On your backend side, if you dont have header with key = "Sec-WebSocket-Protocol" and value of one of your protocols, you will always get this error on chrome.
In my case, it was fine with Firefox

React JS : Module Build Failuer, error showing in render colon

I am getting error like this
Module build failed: SyntaxError
It gives me error in colon of render function
Here it is my code :
webpack.config.js
module.exports = {
entry : './main.js',
output : {
path : './',
filename : 'index.js'
},
devServer : {
inline : true,
port : 3333
},
module : {
loaders : [
{
test : /\.js$/,
exclude : /node_modules/,
loader : 'babel',
query :{
presets : ['es2015', 'react']
}
}
]
}
package.json
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^6.5.2",
"babel-core": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"react": "^15.0.2",
"react-dom": "^15.0.2"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.9.0",
"babel-loader": "^5.3.2"
}
main.js
import React from 'react';
import ReactDom from 'react-dom';
var Heading = React.createClass({
render : function() {
return <th>{this.props.heading}</th>;
}
});
var Headings = React.createClass({
render : function(){
var headings = this.props.headings.map(function(heading) {
return(<Heading heading = {name}/>);
});
return (<thead><tr>{headings}</tr><thead>);
}
});
var Row = React.createClass({
render : function() {
return (
<tr>
<td>{this.props.changeSet.when}</td>
<td>{this.props.changeSet.who}</td>
<td>{this.props.changeSet.description}</td>
</tr>
);
}
});
var Rows = React.createClass({
render : function() {
var rows = this.props.changeSets.map(function(changeSet) {
return(<Row changeSet = {changeSet} />);
});
return <tbody>{rows}</tbody>;
}
});
var App = React.createClass({
render : function() {
return (
<table className='table'>
<Headings headings={this.props.headings} />
<Rows changeSets={this.props.changeSets} />
</table>
);
}
});
/* Data Declaration */
var data = [
{
"when": "2 minutes ago",
"who": "Jill Dupre",
"description": "Created new account"
},
{
"when": "1 hour ago",
"who": "Lose White",
"description": "Added fist chapter"
},
{
"when": "2 hours ago",
"who": "Jordan Whash",
"description": "Created new account"
}
];
var headings = ['When','Who', 'Description'];
/* Call to Render Function for entire app */
ReactDom.render(<App headings={headings} changeSets={data} />, document.getElementById('container'));
Can somebody please provide a solution for it. I have included babel-core also but can't figure out what's wrong.
I tried setting up your code locally and was able to resolve the issue.
I was getting a Module build failed: ReferenceError: [BABEL] - path to file error
The reason is, The node API for babel has been moved to babel-core.So remove the babel dependency from both dependencies and devDependencies, move the babel-loader to your dependencies and clear the devDependencies of your package.json file and reinstall your modules. It should work
There are some syntax errors on
line 20 render : function(){
unclosed tags in line 15 return (<thead><tr>{headings}</tr><thead>);

Token must be defined! error

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'))
});

Resources