Error when using Angular 2 bindings to inject a service - javascript

I have this script that I am converting to es5 using babel
import {Component, View} from 'angular2/angular2';
class Images {
getImagesURLs() {
return ["images/Desert.jpg", "images/Chrysanthemum.jpg", "images/Hydrangeas.jpg", "images/Jellyfish.jpg", "images/Lighthouse.jpg"];
}
}
#Component({
selector: 'home',
bindings: [Images]
})
#View({
template: '<div>Home</div>'
})
export class Home {
constructor(images) {
this.images = images.getImagesURLs();
}
}
I'm getting the following error
Cannot resolve all parameters for Home(?). Make sure they all have valid type or annotations.
Do I need to change this code somehow? Or maybe a Babel or SystemJS configuration?

That is a pretty old example.
Back in the day, where you had atScript, you could achieve that with traceur (not so sure about babel). You could tell it to activate typing and annotation so that code would work perfectly without Typescript.
Today, if you want to achieve that you need to activate stage 1 on babel and then use the proper syntax for injection:
import {Inject} from 'angular2/angular2';
And then in the constructor:
constructor(#Inject(Images) image) {}
If that doesn't work, you can teach babel those new tricks:
npm install babel-plugin-angular2-annotations
npm install babel-plugin-type-assertion
Finally, you can configure babel (.babelrc) like:
{
"optional": ["es7.decorators"],
plugins: [
"angular2-annotations",
"type-assertion"
]
}
Then you can do:
constructor(image:Images) {}

Related

How to use JavaScript files in angular

I am trying to call the javascript function into the angular here is the plugin I am using "npm I global payments-3ds" of which I copied javascript files from node_modules and tried to call in my component
Below is the example :
import {
Component,
OnInit
} from '#angular/core';
import {
handleInitiateAuthentication
} from './globalpayments-3ds/types/index';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular';
ngOnInit(): void {
const status: any = "CHALLENGE_REQUIRED"
const resp = {
challenge: {
encodedChallengeRequest: "abcd",
requestUrl: "url,
},
challengeMandated: "MANDATED",
dsTransactionId: "44444",
id: "444444",
status: status,
};
const windowSize: any = "WINDOWED_600X400";
const displayMode: any = "lightbox";
const challengeWindow = {
windowSize: windowSize,
displayMode: displayMode,
};
handleInitiateAuthentication(resp, challengeWindow)
}
}
I am trying to call the handleInitiateAuthentication() which is giving me the below error
Here is the file structure
from index.d.ts i am calling the handleInitiateAuthentication() function
Here is Stackblitz code for the same
https://stackblitz.com/edit/angular-vodezz?file=src%2Fapp%2Fapp.component.ts
Please help I never used the js function in angular I tried to add in assets not worked
I have tried to create an angular library and add the js files in it and update the package, by converting the file to .tgz but nothing working it showing always the same error,
Why am I doing is I have to update one of the files from node_modules, basically I wanna change files from node modules which is why i copied those files locally
this is also giving error
You have to import directly js file.
// #ts-ignore
import { handleInitiateAuthentication } from './globalpayments-3ds/globalpayments-3ds.esm.js';
For error about module, it's because you have to define type of your module in TypeScript. You can directly use // #ts-ignore.
See this stackblitz : https://stackblitz.com/edit/angular-xz4kmp?file=src%2Fapp%2Fapp.component.ts
You don't need to import a library like that. First of all install the library to your project:
npm i globalpayments-3ds --save
then in your ts file:
import { handleInitiateAuthentication } from 'globalpayments-3ds';
see this stackblitz
The recommended way to make your own modified versions from open source libraries is to fork them and build your own versions.
Also note that you must take into account the license of that NPM package which in the case of https://github.com/globalpayments/globalpayments-js is GPL-v2, so if you will use it for commercial purposes you must follow the agreement. Check this branch: GNU General Public License (v2): can a company use the licensed software for free?.
Taking a look to your Stackblitz code, you may notice that there are several JS versions of the same module in src/app/global-payments-3ds/ folder:
globalpayments-3ds.js (CommonJS, used in Node environments).
globalpayments-3ds.min.js (CommonJS minified).
globalpayments-3ds.js.map (CommonJS minified map file to reference during debugging).
globalpayments-3ds.esm.js (ESM, ECMA Standard Module).
...
To use an external JS Module in an Angular App, as it is JavaScript and not TypeScript, you must tell TypeScript Compiler that you want to allow JS modules by enabling allowJS: true in tsconfig.ts file at the root of the project.
After that you should be be able to import the ESM version (globalpayments-3ds.esm.js) in your Angular App, or if you want to use the CommonJS version, you can also enable esModuleInterop: true in tsconfig.ts to allow importing CommonJS/AMD/UMD JS modules in your project, like globalpayments-3ds.js.

How to use Panzoom javascript in Angular 8+?

I am unable to use Panzoom Javascript library in Angular. I get
ERROR
Error: panzoom is not defined
Here is the stackblitz of what i have done till now .
Here is the working demo of how it should work
Can any one help me troubleshoot ? Thanks
I have followed all the steps mentioned in this post
It seems Panzoom does have typescript definitions Github Issue
here is a working stackblitz
import { Component, AfterViewInit, ElementRef, ViewChild } from '#angular/core';
import panzoom from "panzoom";
#Component({
selector: 'hello',
template: `<img id="scene" #scene src="https://www.probytes.net/wp-content/uploads/2018/01/5-1.png">`,
styles: []
})
export class HelloComponent implements AfterViewInit {
#ViewChild('scene', { static: false }) scene: ElementRef;
ngAfterViewInit() {
// panzoom(document.querySelector('#scene'));
panzoom(this.scene.nativeElement);
}
}
There is an easy way to do this.
Open your angular project in cmd terminal (root of your project, the same foler which contains /src).
Type npm install panzoom --save (that will add panzoom npm package to your angular.json and install it).
In your component add import import * as panzoom from "panzoom" (your project should automaticaly link it with the right file from node_modules.
in ngOnInit or anywhere needed add this line panzoom.default(document.querySelector('#lipsum'));
You should generally incject this PanZoom package in your component constructor after importing it from node_modules but I'm not sure if there is an integration provided by an author.
Definitely check NPM documentation of this plugin for more info

How to use Chrome Extension Api with Angular?

I am working on a chrome extension, I have a "background.js" which it filters the url and fetchs data from my api. When the conditions is meet I am sending a message from "background.js". And I want to catch it from Angular component.
background.js
...
chrome.pageAction.show(tab.id, () => {
chrome.runtime.sendMessage({data: dataFromAPI})
});
...
I ran npm install --save #types/chrome.
app.component.ts
import {Component} from '#angular/core';
import {chrome} from '#types/chrome';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
chrome.runtime.onMessage.addListener( data => console.log(data));
}
}
But WebStorm says, ".../node_modules/#types/chrome/index.d.ts' is not a module. "
How can I use Chrome Api from Angular Component?
/// <reference types="chrome"/>
import {chrome} from '#types/chrome';
// Remove chrome import
IMPORTANT: Must add three slashes before reference.
If still it doesn't work then add "Chrome" in tsconfig.json types.
compilerOptions: ["types": [ "Chrome" ] ]
Add the line
///<reference types="chrome"/>
to the very top of your TS file (preferably line 1). (DO NOT OMIT THE 3 SLASHES IN THE BEGINNING)
Also run the command
npm install --save #types/chrome
Things will start working after that.
In my case, I installed npm install --save #types/chrome
so file stop showing an error Cannot find name 'chrome' when build
then I'm trying to build the library by using the command ng build but it was broken because it didn't find a chrome so what I did?
I added this line ///<reference types="chrome"/> on top of file public-api.ts
Note: Must add three slashes(///) before reference.

Trying to use external Javascript library in angular 5

I'm aware there are similar questions but I still can not get it to work..
So I want to use slick.js so I downloaded the files and put it in my assets folder in my angular application
Ive imported the libraries in my
angular.cli.json
"styles": [
"./assets/scripts/slick-1.8.0/slick.css",
"./assets/scripts/slick-1.8.0/slick-theme.css"
],
"scripts": [
//jQuery imports above
"./assets/scripts/slick-1.8.0/slick.min.js"
]
then In my component...
import { Component, OnInit, Injector } from '#angular/core';
import { AppComponentBase } from '#shared/common/app-component-base';
import * as Slick from '../../../../assets/scripts/slick-1.8.0/slick/slick.min.js';
#Component({
selector: 'app-di-type2',
templateUrl: './di-type2.component.html',
styleUrls: ['./di-type2.component.scss']
})
export class DiType2Component extends AppComponentBase implements OnInit {
public constructor(
injector: Injector
) {
super(injector);
}
ngOnInit() {
const slideContainer = document.querySelector('.slider');
slideContainer.slick({
autoplay: true,
autoplaySpeed: 3500,
});
}
}
from what Ive read about importing external javascript libraries into angular application this should work.. Im getting an error in vscode that says [ts] Property 'slick' does not exist on type 'Element'.any
and then in my console im getting
any help would be appreciated!
Thanks!
Install Slick.js using Node and NPM
https://nodejs.org/
npm install slick-carousel --save
https://www.npmjs.com/package/slick-carousel
Once you install this npm, it'll be saved as a dependency in your package.json file.
Then import Slick:
import 'slick-carousel';
someElement.slick();
You can declare the library as a var of type "any" (assuming it has no typing definitions *.d.ts) after your imports in your component if you import the script in your index.html:
declare let <yourlib>: any;

Decorators with babel, unexpected token

I'm trying to use decorators on classes in React, using babelify. I have the 'es7.decorators' option applied in babel, but I keep getting an 'unexpected token' error when it encounters the '#' character.
Anyone have any ideas? A simple example is below.
Decorator:
export default function(Component) {
return class extends Component {
constructor() {...}
}
}
Class:
import myDecorator from 'decorator';
#myDecorator
class MyClass{...}
I'm using babelify (Browserify transform for Babel):
browserify().transform(babelify.configure({
optional: ['es7.decorators']
})
Thanks to #LeonidBeschastny for mentioning .babelrc file, using the config file decorators work correctly, using the setup described on the babelify readme doesn't work, for whatever reason (not sure if my setup or something else).
In case anyone else ran into this problem, I was having the same problem.
I think there were breaking changes outlined here: http://babeljs.io/blog/2015/03/31/5.0.0/#babelrc
All I needed to do was add { "stage": 1 } to my babelrc, which tells babel to compile with the experimental features, one of which is the es7 decorator.

Categories

Resources