Angular 2 quickstart demo doesn't work - javascript

I am new to Angular 2 and to get started, I download Quickstart project from the official website.
But it shows me the following error in console:
GET
http://localhost:3000/node_modules/#angular/platf...-dynamic/bundles/platform-browser-dynamic.umd.js
304 Not Modified 87ms zone.js (line 2019) GET
http://localhost:3000/systemjs-angular-loader.js 404 Not Found
2ms zone.js (line 2019)
"NetworkError: 404 Not Found -
http://localhost:3000/systemjs-angular-loader.js" systemj...ader.js
Unhandled Promise rejection: Permission denied to access property
"then" ; Zone: ; Task: Promise.then ; Value: Error: Permission
denied to access property "then"
resolvePromise#http://localhost:3000/node_modules/zone.js/dist/zone.js:622:21
scheduleResolveOrReject/<#http://localhost:3000/node_modules/zone.js/dist/zone.js:716:17
ZoneDelegate.prototype.invokeTask#http://localhost:3000/node_modules/zone.js/dist/zone.js:367:17
Zone.prototype.runTask#http://localhost:3000/node_modules/zone.js/dist/zone.js:166:28
drainMicroTaskQueue#http://localhost:3000/node_modules/zone.js/dist/zone.js:546:25
ZoneTask/this.invoke#http://localhost:3000/node_modules/zone.js/dist/zone.js:424:25

change your systemjs.config.js with this systemjs.config.js
(function (global) {
System.config({
map: {
'rxjs': 'node_modules/rxjs',
'#angular': 'node_modules/#angular',
'app': './app',
'angular2-in-memory-web-api' : 'node_modules/angular2-in-memory-web-api'
},
packages: {
'app': {
main: 'main.js',
defaultExtension: 'js'
},
'#angular/platform-browser': {
main: 'bundles/platform-browser.umd.js'
},
'#angular/core': {
main: 'bundles/core.umd.js'
},
'#angular/http': {
main: 'bundles/http.umd.js'
},
'#angular/compiler': {
main: 'bundles/compiler.umd.js'
},
'#angular/compiler-cli': {
main: 'index.js'
},
'#angular/router': {
main: 'bundles/router.umd.js'
},
'#angular/upgrade': {
main: 'bundles/upgrade.umd.js'
},
'#angular/forms': {
main: 'bundles/forms.umd.js'
},
'#angular/common': {
main: 'bundles/common.umd.js',
defaultExtension: 'js'
},
'#angular/platform-browser-dynamic': {
main: 'bundles/platform-browser-dynamic.umd.js'
},
'#angular/platform-server': {
main: 'bundles/platform-server.umd.js'
},
'rxjs': {
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);

It seems that Angular.io team included systemjs-angular-loader.js into the plunker links, however forgot to include the file into downloadable projects.
Please add systemjs-angular-loader.js to the same level as systemjs.config.js
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function(load){
var url = new URL(load.address);
var basePathParts = url.pathname.split('/');
if (url.href.indexOf('plnkr') != -1) {
basePathParts.shift();
basePathParts.shift();
}
basePathParts.pop();
var basePath = basePathParts.join('/');
load.source = load.source
.replace(templateUrlRegex, function(match, quote, url){
let resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return `templateUrl: '${resolvedUrl}'`;
})
.replace(stylesRegex, function(match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push(`'${basePath.substr(1)}${match[2].substr(1)}'`);
} else {
urls.push(`'${match[2]}'`);
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};
Code taken from here:
https://angular.io/resources/live-examples/forms/ts/eplnkr.html

systemjs-angular-loader.js is a new module mentioned in the Change Log for March 13, https://angular.io/docs/ts/latest/guide/change-log.html, but I have yet to find it.

The issue is pointed out in the first lines of your error log:
GET http://localhost:3000/systemjs-angular-loader.js 404 Not Found 2ms zone.js (line 2019)
Which means systemjs-angular-loader.js file is missing in your project.
As #TimFogarty mentioned in his answer, systemjs-angular-loader.js is a new module added to Angular 4.0.
Since the official docs still don't shed light on what should be inside the systemjs-angular-loader.js and even Angular-CLI doesn't generate it, I believe the only option is to take it from the official Angular Quickstart project.
Just for reference, here is its current version:
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function(load){
if (load.source.indexOf('moduleId') != -1) return load;
var url = document.createElement('a');
url.href = load.address;
var basePathParts = url.pathname.split('/');
basePathParts.pop();
var basePath = basePathParts.join('/');
var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;
if (!baseHref.startsWith('/base/')) { // it is not karma
basePath = basePath.replace(baseHref, '');
}
load.source = load.source
.replace(templateUrlRegex, function(match, quote, url){
var resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return 'templateUrl: "' + resolvedUrl + '"';
})
.replace(stylesRegex, function(match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push('"' + basePath + match[2].substr(1) + '"');
} else {
urls.push('"' + match[2] + '"');
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};

I am using Angular 4.3.2, a recent but not the latest version, and I do not have systemjs-angular-loader.js in my package.json file. I do not get the OP's 404 error. Does this mean systemjs-angular-loader.js is now buried somewhere in version 4.x.y?
On the other hand, if I remove moduleId: module.id from the #Component in my app.component.ts, the page no longer loads. It feels like some code change has been made, hinted at in the documentation changelog https://devdocs.io/angular~2/guide/change-log, but not described in Angular Changelog https://github.com/angular/angular/blob/master/CHANGELOG.md or Getting Started documentation. There are no examples (before -> after) to be found in Angular documentation.
The answer needs to come in official Angular code documentation - with before -> after examples. Then reference it here.

Related

Javascript module include in protractor configuration js file

I have created a customized-jasmin-allure-reporter.js class where I wrote the report configuration methods similar like jasime2Allure reporter module except some minor changes. Now I would like to include this file into protractor configuration.js file from where I want to generate custome allure report using this. But unfortunately I found error all the time Error: Error: Cannot find module 'customized-jasmin-allure-reporter'.
MyCustomized class is
var Allure = require('allure-js-commons');
var path = require('path');
var allure = new Allure();
function CustomizedJasminAllureReporter(userDefinedConfig, allureReporter) {
var Status = {PASSED: 'passed', FAILED: 'failed', BROKEN: 'broken', PENDING: 'pending'};
this.allure = allureReporter || allure;
..................
}
exports.allureReporter = allure;
exports.CustomizedJasminAllureReporter =CustomizedJasminAllureReporter;
My Protractor configuration file is
exports.config = {
troubleshoot: true, // for protractor
allScriptsTimeout: 1500000,
restartBrowserBetweenTests: false,
specs: [
'./e2e/tests/**/*.e2e-spec.ts',
],
capabilities:
{
'browserName' : 'chrome',
'chromeOptions': { 'args' : ['--disable-extensions']},
'shardTestFiles': true,
'maxInstances': 1,
'unexpectedAlertBehaviour' : 'dismiss'
},
..............
onPrepare: function() {
var AllureReporter = require('customized-jasmin-allure-reporter');
// get the browser name
var capsPromise = browser.getCapabilities();
capsPromise.then(function(caps) {
console.log(caps);
var browserName = caps.get('browserName');
var browserVersion = caps.get('version');
browser.browserNameforSpec = browserName + "-" + browserVersion + "-";
console.log(browser.browserNameforSpec);
});
browser.manage().window().maximize();
require('ts-node').register({
project: 'e2e/tsconfig.json'
});
jasmine.getEnv().addReporter(new AllureReporter({
resultsDir: 'allure-results'
}));
jasmine.getEnv().addReporter(reporter);
jasmine.getEnv().afterEach(function (done) {
browser.takeScreenshot().then(function (png) {
allure.createAttachment('Screenshot', function () {
return new Buffer(png, 'base64')
},'image/png')();
done();
})
});
}
};
Your custom reporter is not imported properly.
`var AllureReporter = require('./src/...');` //Provide relative or absolute path of your report file.

Can Some give an elaborate example of using Custom Jasmine Reporter for protractor. I am unable to understand Tutorial

Can Some give an elaborate example of using Custom Jasmine Reporter . I would like someone to help me with a sample test with two assertions . how to add the reporter in protractor conf.js and how it can help me . No where in the internet there is a example apart from just the reference .
check the one I use:
First check if all the necessary dependencies are installed (check the begin of the code)
Then copy+paste this to you Conf.js:
//In my case I installed the dependencies locally thats why comes from lib folder
var jasmineReporters = require('./lib/node_modules/jasmine-reporters');
var HTMLReport = require('./lib/node_modules/protractor-html-reporter-2');
var fs = require('./lib/node_modules/fs-extra');
onPrepare: function () {
fs.emptyDir('./Execution_Results/reports/xml/', function (err) {
if (err != ""){
console.log(err);
}
});
fs.emptyDir('./Execution_Results/reports/results/screenshots', function (err) {
if (err != ""){
console.log(err);
}
});
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: './Execution_Results/reports/xml/',
filePrefix: 'xmlresults'
}));
jasmine.getEnv().addReporter({
specDone: function (result) {
//if (result.status == 'failed') {
browser.getCapabilities().then(function (caps)
{
var browserName = caps.get('browserName');
browser.takeScreenshot().then(function (png) {
var stream = fs.createWriteStream('./Execution_Results/reports/results/screenshots/' + browserName + '-' + result.fullName + '.png');
stream.write(new Buffer(png, 'base64'));
stream.end();
});
});
//}
}
});
},
//HTMLReport called once tests are finished
onComplete: function() {
var browserName, browserVersion;
var capsPromise = browser.getCapabilities();
capsPromise.then(function (caps) {
browserName = caps.get('browserName');
browserVersion = caps.get('version');
platform = caps.get('platform');
testConfig = {
reportTitle: 'Protractor Test Execution Report',
outputPath: './',
outputFilename: 'Execution_Results/reports/results/IV2_Test_Results',
screenshotPath: './screenshots/',
testBrowser: browserName,
browserVersion: browserVersion,
modifiedSuiteName: false,
screenshotsOnlyOnFailure: true,
testPlatform: platform
};
new HTMLReport().from('./Execution_Results/reports/xml/xmlresults.xml', testConfig);
});
},
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
// If true, display spec names.
isVerbose: true,
},
the folders will be created automatically inside the folder where your conf.js is located so after the execution just access the 'Execution_Results/reports' and open the html report
OnPrepare will generate the xml file with all the results
OnComplete will transform the xml into html report
I'm using this reporter, Just follow the steps from this link to set the conf.js https://www.npmjs.com/package/protractor-jasmine2-screenshot-reporter

karma-test-shim.js calling TestBed.initTestEnvironment, but no effect. TestBed must be initialized again

I am currently trying to get unit testing working with Angular2 final and karma + jasmine.
I have the following problem:
TypeError: Cannot read property 'injector' of null if don't add: TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting())
.configureTestingModule({
declarations: [],
providers: [Stuff],
imports: [Stuff]
});
To my test.
But I can only call the initTestEnvironment and configureTestingModule once, so more than 1 test is not possible. And I'd like to prevent having an init test.
Here is my karma-test-shim.js
// #docregion
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.
// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
// Error.stackTraceLimit = Infinity; //
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
var builtPath = '/base/app/';
__karma__.loaded = function () { };
function isJsFile(path) {
return path.slice(-3) == '.js';
}
function isSpecFile(path) {
return /\.spec\.(.*\.)?js$/.test(path);
}
function isBuiltFile(path) {
return isJsFile(path) && (path.substr(0, builtPath.length) == builtPath);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isBuiltFile);
System.config({
baseURL: '/base',
// Extend usual application package list with test folder
packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } },
// Assume npm: is set in `paths` in systemjs.config
// Map the angular testing umd bundles
map: {
'#angular/core/testing': 'npm:#angular/core/bundles/core-testing.umd.js',
'#angular/common/testing': 'npm:#angular/common/bundles/common-testing.umd.js',
'#angular/compiler/testing': 'npm:#angular/compiler/bundles/compiler-testing.umd.js',
'#angular/platform-browser/testing': 'npm:#angular/platform-browser/bundles/platform-browser-testing.umd.js',
'#angular/platform-browser-dynamic/testing': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
'#angular/http/testing': 'npm:#angular/http/bundles/http-testing.umd.js',
'#angular/router/testing': 'npm:#angular/router/bundles/router-testing.umd.js',
'#angular/forms/testing': 'npm:#angular/forms/bundles/forms-testing.umd.js',
},
});
System.import('systemjs.config.js')
.then(importSystemJsExtras)
.then(initTestBed)
.then(initTesting);
/** Optional SystemJS configuration extras. Keep going w/o it */
function importSystemJsExtras(){
return System.import('systemjs.config.extras.js')
.catch(function(reason) {
console.log(
'WARNING: System.import could not load "systemjs.config.extras.js"; continuing without it.'
);
console.log(reason);
});
}
function initTestBed(){
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
])
.then(function (providers) {
var coreTesting = providers[0];
var browserTesting = providers[1];
console.log("call initTestEnvironment")
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
console.log("call configure teting module")
coreTesting.TestBed.configureTestingModule({
declarations: [],
providers: [],
imports: []
})
})
}
// Import all spec files and start karma
function initTesting () {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
})
)
.then(__karma__.start, __karma__.error);
}
I thought calling the initTestEnvironment in the test shim is enough. I am surprised that I the call in the karma-test-shim.js seems to have no effect.
package.json and code are in a related question: AsyncTestCompleter Browserify Angular2 HTTP Mock Test
Thank you so much for your help.

gulp-task output in console is not printing expected result

I have the following gulp task which inserts .css and .js files in the html file:
gulp.task('inject', function () {
log('Injecting the JS and CSS files into index.html');
var wiredep = require('wiredep').stream;
var options = config.getWiredepDefaultOptions();
return gulp.src(config.index)
.pipe(wiredep(options))
.pipe($.inject(gulp.src(config.customFiles), {ignorePath: options.ignorePath}))
.pipe(gulp.dest(config.client));
});
and my gulp.config.js:
module.exports = function () {
var client = './public';
var config = {
allJS: [
'*.js',
'public/js/*.js',
'public/js/**/*.js'
],
client: client,
index: client + '/index.html',
customFiles: [
'./public/css/*.css',
'./public/js/*.js',
'./public/js/**/*.js'
],
bower: {
json: require('./bower.json'),
directory: './public/lib',
ignorePath: '/public/'
},
};
config.getWiredepDefaultOptions = function () {
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
This works as expected, but when I run the task I get this:
It always says gulp-inject 3 files into index.html, even though no new files was added.
Is there something wrong with my gulp file?
Well if you are using gulp-inject this is what I found.
If you look at the code in gulp-inject you can see it just spits out the file count unless it gets opt.quiet set. I didn't see a option in the docs for this setting but if you look at the tests it shows an example it being used.
Enabling quiet mode link line 505
inject(sources, {quiet: true});
Source where it generates the log statement. link line 109
function getNewContent(target, collection, opt) {
var logger = opt.quiet ? noop : function (filesCount) {
if (filesCount) {
log(cyan(filesCount) + ' files into ' + magenta(target.relative) + '.');
} else {
log('Nothing to inject into ' + magenta(target.relative) + '.');
}
};

grunt load dynamic JSON file

Is it possible to load a JSON file from a dynamic source? I want to do some localisation
grunt.file.readJSON('src/locales/<%= grunt.task.current.args[0] %>/i18n.json');
A fuller example of the Gruntfile looks like:
module.exports = function(grunt) {
var i18n = {
locales: ['en', 'fr', 'de', 'es'],
default: 'en',
replacements: function(locale){
var content = grunt.file.readJSON('src/locales/<%= grunt.task.current.args[0] %>/i18n.json');
var arr = [];
for(i in content){
var replacement = {
from: i,
to: content[i].value
};
arr.push(replacement);
}
return arr;
}
};
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
replace: {
build: {
src: ['local/en/**/*.html'], // source files array (supports minimatch)
dest: 'local/<%= grunt.task.current.args[0] %>/', // destination directory or file
replacements: i18n.replacements('<%= grunt.task.current.args[0] %>')
}
},
While registering the task looks like:
grunt.registerTask('localise', function(){
var tasks = [];
for(i in i18n.locales){
if(i18n.locales[i] !== i18n.default){
tasks.push('replace:build:' + i18n.locales[i]);
}
}
grunt.task.run(tasks);
});
Everything works as I'd hoped except loading the JSON to actually do the replacements.
I've also tried:
grunt.file.readJSON('src/locales/'+locale+'/i18n.json');
which didn't work either, leaving me a little stumped.
Anyone able to help?
Thanks
Try:
'src/locales/' + grunt.task.current.args[0] + '/i18n.json'
Ok, I got it working after much trial and error:
I updated the function returning the data to:
var i18n = {
locales: ['en', 'fr', 'de', 'es'],
default: 'en',
replacements: function(locale){
var content = grunt.file.readJSON('src/locales/'+ locale +'/i18n.json');
var arr = [{from: "/" + locale, to: "/en"}, {from: "Test", to: locale}];
for(i in content){
var replacement = {
from: i,
to: content[i].value
};
arr.push(replacement);
}
console.log(arr);
return arr;
}
};
Then set an empty array in the default task:
replace: {
build: {
src: ['local/en/**/*.html'], // source files array (supports minimatch)
dest: 'local/<%= grunt.task.current.args[0] %>/', // destination directory or file
replacements: []
}
},
Which is updated using it's own task
grunt.registerTask('updateConf', function(locale){
var content = i18n.replacements(locale);
grunt.config('replace.build.replacements', content);
});
That is run just before the replace task:
grunt.registerTask('localise', function(){
var tasks = [];
for(i in i18n.locales){
if(i18n.locales[i] !== i18n.default){
tasks.push('updateConf:' + i18n.locales[i]);
tasks.push('replace:build:' + i18n.locales[i]);
}
}
grunt.task.run(tasks);
});
Giving the right output. Probably not the most elegant of solutions but it works!

Categories

Resources