Injectables in Angular2

后端 未结 3 1207
无人及你
无人及你 2021-01-17 12:12

I am playing around with Angular2. As a basis, I used the quickstart project from the angular.io page.

Everything seems to work fine, but as soon as I try to inject

3条回答
  •  清酒与你
    2021-01-17 12:25

    Check for couple of things:-

    1) Make sure you are using the correct version of typescript (1.5.x) installed from your package location. () If you have previous versions of typescript installed then merely using "tsc" command could be pointing to the existing (< 1.5) location from the environment path.

    2) Make sure you use --emitDecoratorMetadata flag with the tsc command. It is necessary so the javascript output creates the metadata for the decorators.

    3) Error - Cannot read property 'annotations' of undefined Because AppComponent directive has a dependency on DetailComponent which has not been defined yet (by the time the synchronous __decorate( function runs to resolve the dependencies) and the way TS compiles the hoisted variable DetailComponent is undefined then (The IIFE for that below is yet to run). Try moving the declaration of DetailComponent before AppComponent. Or just move it to a different file and import it.

    @Component({
        selector: 'item-details',
        properties: {
            item: "item"
        }
    })
    @View({
        template: `You selected {{item.name}}`
    })
    class DetailComponent {
        item:Item;
    }
    
    @Component({
        selector: 'app',
        injectables: [ItemService]
    })
    @View({
        template: `

    Testing Angular2

    `, directives: [For, If, DetailComponent] }) class AppComponent { items:Item[]; selectedItem:Item; constructor(itemService:ItemService) { this.items = itemService.getItems(); } toggleSelected(item) { this.selectedItem = this.selectedItem == item ? null : item; return false; } } bootstrap(AppComponent);

    Edit

    As of angular a26 if you face issues with respect to following the current documentation (as of now) follow this link if it helps as there are some relevant changes.

提交回复
热议问题