简体   繁体   中英

Upgrade AngularJS factory (ES5) to be used in Angular2 (TypeScript)

I am trying to create an application using Angular2 and TypeScript with SystemJS as module loader.
I allready have a working AngularJS 1.X with a corresponding framework, written in JavaScript (ES5) and using some basic functions of Google Closure .
Now i would like to use some functionality of that framework inside my Angular2 app.
I have been reading a few tutorials about the Angular2 UpgradeAdapter , including this one , where they say:

It doesn't really make sense to upgrade existing code to ES2015 or TypeScript.
If we have to upgrade to Angular 2, it probably makes more sense to just rewrite component by component.

To me this sounds like it is possible to use AngularJS (ES5) components/services in Angular2 (TypeScript) and vice versa.
However i am having problems when trying to upgrade a AngularJS factory to be used in my Angular2 Component .

The situation:

I have a file webclient.js .
It provides a namespace my.webclient (using goog.provide ).
Inside a goog.scope -function it then defines a angular.module called my.webclient .
Then a factory named getWebclient is created using module.factory .
This factory returns a function , which returns a Promise .
Now i would like to use this factory ( getWebclient ) inside my Angular2 Component .

My Angular2 Component looks like this:

import {Component, Inject} from "angular2/core";
import {bootstrap} from "angular2/platform/browser";
import adapter from "./upgrade";    // adapter is a new UpgradeAdapter()

adapter.upgradeNg1Provider("getWebclient");

@Component({
    selector: "my-app",
    templateUrl: "path-to-tamplate/app.html"
})
export class AppComponent {

    constructor(@Inject("getWebclient") getWebclient) {
        getWebclient().then(webclient => {
            // If the Promise succeed i'll can log the webclients name property.
            console.log(webclient.name);
        })
    }
}

bootstrap(AppComponent);

However this results in a DI Exception with the message

No provider for getWebclient! (AppComponent -> getWebclient).

How can i solve this problem?

Thanks

EDIT:

I changed the bootstrap line to

upgradeAdapter.bootstrap(document.body, ["my.webclient"], {strictDi: true});

and now there aren't any errors. However, now the AppComponent does not seem to be loaded into the DOM, using the <my-app/> tag.

Try this link, there are some useful details: https://angular.io/docs/ts/latest/guide/upgrade.html

For one thing: you should no longer use <my-app/> tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM