EDIT: I tried to apply the fix #Thierry provided in his answer, however I keep getting the same error.
I created a repository with the full project (clean with no comments) as it resulted by following the tutorial and after applying #Thierry's fix: https://github.com/dragGH102/angular2-tutorial-part4-test
I am following tutorial for Angular 2 at https://angular.io/docs/ts/latest/tutorial/toh-pt4.html
At the end of part 4 I am getting the following error:
SyntaxError: Unexpected token <(…)Zone.run # angular2-polyfills.js:1243
I even tried to:
copy-paste the Plunkr provided at http://plnkr.co/edit/?p=preview but same error.
remove the Promise part (which seems to be the cause of the error based on the stacktrace below)
compile TS files myself (instead of letting it do by "npm start")
Error stacktrace
SyntaxError: Unexpected token <(…)
Zone.run # angular2-polyfills.js:1243
zoneBoundFn # angular2-polyfills.js:1220
lib$es6$promise$$internal$$tryCatch # angular2-polyfills.js:468
lib$es6$promise$$internal$$invokeCallback # angular2-polyfills.js:480
lib$es6$promise$$internal$$publish # angular2-polyfills.js:451
lib$es6$promise$$internal$$publishRejection # angular2-polyfills.js:401
(anonymous function) # angular2-polyfills.js:123
Zone.run # angular2-polyfills.js:1243
zoneBoundFn # angular2-polyfills.js:1220
lib$es6$promise$asap$$flush # angular2-polyfills.js:262
Apparently (e.g. angular2: Uncaught SyntaxError: Unexpected token < ) this is due to the browser not find valid JS code due to an error but I can't figure out what's wrong .
Here is my code (also available at http://plnkr.co/edit/Q5F0mV8Hbdcr2rtZUSw5 )
index.html
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {'app': {defaultExtension: 'ts'}}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
app.component.ts
import {Component, OnInit} from 'angular2/core';
import {Hero} from './hero';
import {HeroDetailComponent} from './hero-detail.component';
import {HeroService} from './hero.service';
#Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="#hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
`,
// for the sake of code readibility I removed "styles"
directives: [HeroDetailComponent],
providers: [HeroService],
})
export class AppComponent implements OnInit {
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private _heroService: HeroService) { }
getHeroes() {
this.heroes = this._heroService.getHeroes().then(heroes => this.heroes = heroes);
}
ngOnInit() {
this.getHeroes();
}
onSelect(hero: Hero) { this.selectedHero = hero; }
}
boot.ts
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
bootstrap(AppComponent);
hero-detail.component.ts
import {Component} from 'angular2/core';
import {Hero} from './hero';
#Component({
selector: 'my-hero-detail',
template: `
<div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name"/>
</div>
</div>`,
inputs: ['hero']
})
export class HeroDetailComponent {
hero: Hero;
}
hero.service.ts
import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import {Injectable} from 'angular2/core';
#Injectable()
export class HeroService {
getHeroes() {
return Promise.resolve(HEROES);
}
}
hero.ts
export interface Hero {
id: number;
name: string;
}
mock-heroes.ts
import {Hero} from "./hero";
export var HEROES: Hero[] = [
{ "id": 11, "name": "Mr. Nice" },
{ "id": 12, "name": "Narco" },
{ "id": 13, "name": "Bombasto" },
{ "id": 14, "name": "Celeritas" },
{ "id": 15, "name": "Magneta" },
{ "id": 16, "name": "RubberMan" },
{ "id": 17, "name": "Dynama" },
{ "id": 18, "name": "Dr IQ" },
{ "id": 19, "name": "Magma" },
{ "id": 20, "name": "Tornado" }
];
I had a look at your plunkr and the problem comes from this line:
getHeroes() {
this.heroes = this._heroService.getHeroes().then(heroes => this.heroes = heroes);
}
In fact, you mix two approaches:
either you set the promise on a component property and then the async pipe to display data when the promise is resolved
#Component({
selector: 'my-app',
template:`
<li *ngFor="#hero of heroes">
(...)
</li>
`
})
export class AppComponent implements OnInit {
getHeroes() {
this.heroes = this._heroService.getHeroes();
}
}
either you call the then method and set the received data when resolving into a component property. In this case, you don't need the async pipe
#Component({
selector: 'my-app',
template:`
<li *ngFor="#hero of heroes">
(...)
</li>
`
})
export class AppComponent implements OnInit {
getHeroes() {
this._heroService.getHeroes().then(heroes => this.heroes = heroes);
}
}
See my updates in a forked plunkr: http://plnkr.co/edit/Rw4kOzKFbVosaoe7dRL1?p=preview.
Otherwise I can't see any error like SyntaxError: Unexpected token <(…) but most of time it's because you try to load a JS file and you get a 404 error...
See this question for more details:
How to debug Angular2 in Chrome
Related
My App.vue looks like this:
<template>
<HelloWorld />
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue'
// This starter template is using Vue 3 experimental <script setup> SFCs
// Check out https://github.com/vuejs/rfcs/blob/script-setup-2/active-rfcs/0000-script-setup.md
</script>
As you can see, I've imported the Component HelloWorld.
And HelloWorld.vue looks like this:
<template>
<ul>
<li v-for="item in items" :key="item.message">
{{ item.message }}
</li>
</ul>
<h1>OK</h1>
</template>
<script>
const Viewer = {
data() {
return {
items: [{ message: 'Foo' }, { message: 'Bar' }]}
},
}
</script>
The header element "OK" is rendering, but the list messages are not.
I do not know what that Viewer object is. Your template cannot access the items object.
You can use the script setup :
<script setup>
import { ref } from 'vue'
const items = ref([{ message: 'Foo' }, { message: 'Bar' }])
</script>
or the default script :
<script>
import { ref } from 'vue'
export default {
setup (props) {
const items = ref([{ message: 'Foo' }, { message: 'Bar' }])
return { items }
}
}
</script>
In HelloWorld.vue, your script block should be like
<script setup>
import { ref } from 'vue'
export const items = ref([{ message: 'Foo' }, { message: 'Bar' }])
</script>
As you are using <script setup> syntax, you only need this code to make it works:
<script setup>
import { ref } from 'vue'
const items = ref([{ message: 'Foo' }, { message: 'Bar' }])
</script>
No data or return statements are required
I am trying to open a pdf in my ionic 5 application with the plugin
npm i # pdftron / pdfjs-express --save
but ionic shows me the error Cannot match any routes. URL Segment: 'lib / ui / index.html'
please how to correct this error?
my code:
app.component.html
<div class="page">
<div class="header">Angular sample</div>
<div #viewer class="viewer"></div>
</div>
app.component.ts
import { Component, ViewChild, OnInit, ElementRef, AfterViewInit } from '#angular/core';
import WebViewer from '#pdftron/pdfjs-express';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
#ViewChild('viewer', { static: false }) viewer: ElementRef;
wvInstance: any;
ngAfterViewInit(): void {
WebViewer({
path: '../lib',
initialDoc: '../files/webviewer-demo-annotated.pdf'
}, this.viewer.nativeElement).then(instance => {
this.wvInstance = instance;
})
}
ngOnInit() {
}
}
Have you used any of our angular samples here https://github.com/PDFTron?q=angular? You can clone one of the samples and take a look at how it is implemented
I'm trying to integrate openlayer with vuejs.
Whatever i try i still have the following error : Uncaught TypeError: target.addEventListener is not a function
After some research i found some example in vuejs but don't really help me.
I have also try vuelayers. I got the same error.
Any idea ?
EDIT :
openlayers version : "ol": "^6.4.3",
vuejs version : "vue": "^2.6.11",
<template>
<div class="w3-content">
<div ref="map-root" id="map"></div>
</div>
</template>
<script>
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
export default {
data() {
return {
}
},
methods: {
initMap() {
const map = new Map({
target: this.$refs['map-root'],
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: [0, 0],
zoom: 0
})
});
}
},
mounted() {
this.initMap();
}
}
</script>
Im very new to Angular 2 so bear with me.
Im trying to get a new component to appear in the index.html page.
The file set is from the basic quick start files from GitHub.
I created a new component as such:
import { Component } from '#angular/core';
#Component({
selector: 'app-user-item',
template: `<h1>It works!</h1>`,
})
export class UserItemComponent {
}
I have declared the selector tags in HTML as such:
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 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/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
<app-user-item>loading another component</app-user-item>
</body>
</html>
I even tried adding the import to the top of app.module.ts and component name to the declarations array in app.module.ts. But still nothing.
I checked my file structure and there is a js version of user-item.component.ts. But I cannot see changes.
Any help would be appreciated.
Cheers
I had this exact same problem. In your app.module.ts file make sure to include your component in your bootstrap declaration.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { UserItemComponent } from './UserItem.component';
#NgModule({
declarations : [
AppComponent,
UserItemComponent
],
imports: [
BrowserModule
],
bootstrap: [
AppComponent,
UserItemComponent
],
providers: [],
})
export class AppModule { }
user-item.component.ts:
import { Component } from '#angular/core';
#Component ({
selector: 'app-user-item',
template: `<p>child item</p>`
)}
export class UserItemComponent {
constructor(){ }
}
user.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'app-user',
template: ` <h2> My User Item </h2>
<app-user-item></app-user-item>`
})
export class UserComponent {
constructor() {}
}
user.module.ts:
import { NgModule } from '#angular/core';
import { UserComponent } from './user-component';
import { UserItemComponent } from './user-item-component';
#NgModule({
declarations: [
UserComponent,
UserItemComponent
]
})
export class UserModule {}
I really encourage you to use angular-cli (https://github.com/angular/angular-cli). And to do the tutorials on angular page.
However, For your use case the code above should be sufficient and work.
Usually you declare your subcomponent in the same module as the parentcomponent.
This module is imported by the app.module (root module)
Look at the Master-Detail Component Tutorials of Angular
https://angular.io/docs/ts/latest/tutorial/toh-pt2.html
In my case Selector defined in app.component.ts file was not matching with index.html
I trying to create a test against a simple service, but I am getting an error that says "TypeError: Object doesn't support property or method 'map'" When I run this service for real (not as a test) it works fine and I don't have any issues. This is the first time I'm trying to get a test setup for Angular2, so I could be missing something. Here are my components.
recentActivity.service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import * as toPromise from 'rxjs/add/operator/toPromise';
import * as map from 'rxjs/add/operator/map';
import { RecentActivity } from './recentActivity.model';
#Injectable()
export class RecentActivityService {
private baseUrl = '/RecentActivity/';
constructor(private http: Http) {
}
get(): Observable<any> {
//return undefined;
return this.http
.get(this.baseUrl + 'Get')
.map((response: Response) => response.json())
//.toPromise()
;
}
}
recentActivity.spec.ts
import { async, describe, it, expect, inject, beforeEach, beforeEachProviders } from '#angular/core/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '#angular/http';
import { MockBackend, MockConnection } from '#angular/http/testing';
import { RecentActivity } from './recentActivity.model';
import { RecentActivityService } from './recentActivity.service';
describe('Recent Activity Service', () => {
let service: RecentActivityService;
let mockBackend: MockBackend;
const mockResponseData: RecentActivity[] = [
{ Name: 'Test Result 1', Url: '#/TestResult1' },
{ Name: 'Test Result 2', Url: '#/TestResult2' },
{ Name: 'Test Result 3', Url: '#/TestResult3' }
];
beforeEachProviders(() => [
RecentActivityService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}
]);
beforeEach(inject([RecentActivityService, MockBackend], (ras, mb) => {
service = ras;
mockBackend = mb;
}));
it('Can load list of recent activities', (done) => {
mockBackend.connections.subscribe((connection: MockConnection) => {
const responseOpts = new ResponseOptions({ body: JSON.stringify(mockResponseData) });
connection.mockRespond(new Response(responseOpts));
});
service.get()
.subscribe((results: RecentActivity[]) => {
expect(results.length).toEqual(3);
expect(results[0].Name).toEqual('Test Result 1');
expect(results[1].Name).toEqual('Test Result 2');
expect(results[2].Name).toEqual('Test Result 3');
done();
});
});
});
unit-tests.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Unit Tests</title>
<link rel="stylesheet" href="./libs/jasmine-core/lib/jasmine-core/jasmine.css">
<script src="./libs/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="./libs/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="./libs/jasmine-core/lib/jasmine-core/boot.js"></script>
<script src="./libs/core-js/client/shim.min.js"></script>
<script src="./libs/zone.js/dist/zone.js"></script>
<script src="./libs/reflect-metadata/Reflect.js"></script>
<script src="./libs/systemjs/dist/system.src.js"></script>
<script src="./libs/rxjs/bundles/Rx.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/underscore/underscore.js"></script>
<script src="~/lib/moment/moment.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="./systemjs.config.js"></script>
<script>
// #2. Configure systemjs to use the .js extension
// for imports from the app folder
System.config({
packages: {
'app': { defaultExtension: 'js' }
}
});
// #3. Import the spec file explicitly
Promise.all([
System.import('app/recentActivity/recentActivity.spec'),
System.import('app/pipes/styleVisibility.spec')
])
// #4. wait for all imports to load ...
// then re-execute `window.onload` which
// triggers the Jasmine test-runner start
// or explain what went wrong.
.then(window.onload)
.catch(console.error.bind(console));
</script>
</head>
<body>
</body>
</html>
I've tried to piece together the pieces to get this to work, but I can't figure out what I'm missing. Also as a side note I'm using Visual Studio 2015 and that is also giving a warning saying "Property map does not exist on type 'Observable'".
Like I mentioned everything works when I run this service for real and it returns my information from my backend no problem.
All I had to do was change the imports in the recentActivity.service.ts file to be
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
I still get an error (red squiggly) In Visual Studio, so if somebody could tell me how to get rid of that I would appreciate it.
The above solution works for me too. But since I was also using .do and .catch, I had to import those as well:
import 'rxjs/add/operator.do;
import 'rxjs/add/operator.catch;
Hope this helps others also.