angular2 dependency injection error - dependency-injection

i am trying to access a simple method from a service class in a component.
//myfriend.service.ts
export class MyFriendService(){
constructor(){}
testMe() {
window.alert("im friend service");
}
}
//myfriend.component.ts
import {Component} from 'angular2/core';
import {MyFriendService} from 'app/components/myfriend/myfriend.service';
#Component({
directives: [],
providers: [MyFriendService],
templateUrl: `app/components/myfriend/myfriend-view.html`
})
export class MyFriendCmp {
constructor(myFriendService: MyFriendService) {
myFriendService.testMe();
}
}
it is throwing an error
myFriendService.testMe is not a function.
I spent a lot of time in this to get this work.but still trying.Help me to figure this out. Thanks!.

Working Plnkr
Oh can you believe this? It took very long to figure it out. But you have put
not required parenthesis look at this line
export class MyFriendService() <=This parenthesis not required.
I have made two to three plunkr and every time it was working then took lot of time to figure this out that you have made problem with parenthesis.
export class MyFriendService{
constructor(){}
testMe() {
window.alert("im friend service");
}
}

Related

use service as decorator

Is there a way to do a static decorator on routes that check certain logics before loading?
example
have a auth decorator
#Injector()
class Auth{
Auth(){
if (isLoggedIn){
proceed();
}else{
showLoginRoute();
}
}
}
and use like
#Auth()
#Component(
selector: 'auth-view',
styleUrls: const ['login_component.css'],
template:
'<router-outlet name="dashboard" [routes]="routes.authView_routes"></router-outlet>',
directives: const [materialDirectives, routerDirectives, coreDirectives],
providers: const [r.Routes, materialProviders, Auth],
)
class Dashboard{
....
}
I know what i want to do but just not sure how to get it done. Currently i am importing services across several components and doing lots of repetition and i want to avoid that as much as possible.
Dart doesn't support anything like decorators in TS.
What might work for you is code generation like it's done in build_value, json_serializable, ...
https://github.com/dart-lang/build

how to use angular2 in mvc5 areas?

i have a sample mvc5 project and i used my first angular 2 modules successfully on this project. now i want to create new module inside my mvc areas. so i created new area with a .tsfile named app.components in my area solution! like what you see below:
import { Component } from '#angular/core';
#Component({
selector: 'area-app',
template:`<p>imanArea</p>`
})
export class areacomponent {<<bring below error!!!!!!!!!!!
name = 'dd';
}
experimental support for decorators is a feature
that is subject to change in a future release. set the
'experimentaldecorators' option to remove this warning
and second is from my root project rootproj/app/app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms'; // <-- NgModel lives here
import { AppComponent } from './app.component';
***below error for this line***
import { AreaAppComponent } from './Areas/SampleArea/app/app.areacomponent'
#NgModule({
imports: [BrowserModule, FormsModule],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Cannot find module'./Areas/SampleArea/app/app.areacomponent'
i checked my path and file names!! every thing is right but it doesn't find my path!
for more information i have to say all my essential angular files are in my root project and my app.module is inside a folder named app
means: rootProj/app/app.module and rootProj/app/app.component.spec
is it possible to use angular2 and mvc-Area together in one project?? i didnt find any source about that.
I actually use WebAPI to use Angular 2.
Back and Front-End are going to be in different project folders. And you will work with restful services.

Angular2 - inject singleton Service into Directive

I have problem with injecting singleton service into a directive.
I have service:
#Injectable()
export class AuthService{ ... }
I put it into bootstrapper.
bootstrap(AppComponent, [AuthService, ...]);
I made directive, that protects my component:
#Directive({
selector: '[protected]'
})
export class ProtectedDirective {
constructor(private authService:AuthService) { ... }
}
... and added to one of components
#Component({
selector: 'dashboard',
directives: [ProtectedDirective],
template: '<div protected></div',
})
export class DashboardCmp { }
In console i see an error:
ORIGINAL EXCEPTION: No provider for AuthService!
If I add a provider to DashboardCmp, everything works fine, but it's not a singleton service. I set its properties in other component and I don't see them when I'm in directive.
I resolved my problem. Everything was fine but
import {AuthService} from '../services/auth.service'; (in protected.directive.ts)
is not equal to
import {AuthService} from '../Services/auth.service'; ( in main.ts)
Yes, it's stupid, but it made the dependency injection impossible.

Angular2 Beta dependency injection

I have a NavBar Component which loads the QApi Service, the QApi Service loads the UserService, but I get the following error:
EXCEPTION: No provider for UserService! (NavBarComponent -> QApi -> UserService)
Either I simply don't get the concept of dependency injection, I made a stupid error, or this is just way to complicated compared to native development... Thanks for your help.
Here my code:
UserService:
import {Injectable} from 'angular2/core';
//import {User} from '../data-source-mocks/users';
#Injectable()
export class UserService {
public isAuthenticated = true;
}
QApi Service:
import {Injectable} from 'angular2/core';
import {UserService} from '../user/user.service';
#Injectable()
export class QApi {
constructor(private _userService: UserService) {}
}
NavBar Component:
import {Component} from 'angular2/core';
import {QApi} from '../../services/q-api/q-api';
#Component({
selector: 'nav-bar',
template: `Test NavBar`,
providers: [QApi]
})
export class NavBarComponent {
private _isAuthenticated = false;
constructor(private _QApi: QApi) {}
}
EDIT:
First of all: Thanks for alle the great answers each and every single one helped me to understand dependency injection better, especially this article: https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html
I changed my QApi class to this:
import {Injectable, Inject, Injector} from 'angular2/core';
import {UserService} from '../user/user.service';
import {CardService} from '../card/card.service';
#Injectable()
export class QApi {
constructor() {
var _injector = Injector.resolveAndCreate([UserService,
CardService]);
this.userService = _injector.get(UserService);
this.cardService = _injector.get(CardService);
}
}
Now it works like I hoped it would. Cant thank you guys enough!!
Add UserService to the component providers:
#Component({
selector: 'nav-bar',
template: `Test NavBar`,
providers: [QApi, UserService] // <- add UserService here
})
export class NavBarComponent { /* ... */ }
Here are two good articles to better understand Angular2 Dependency Injection:
blog.thoughtram.io: Dependency Injection in Angular2
blog.thoughtram.io: Injecting services in services in Angular 2
In fact both previous responses are true! ;-)
You need to define the services:
Application level. Within the second parameter of the bootstrap function. It contains the list of the providers that are available for the whole application.
bootstrap(App, [UserService, QApi, ...]);
Component level. Within the providers attribute of the Component annotation. In this case, this is only configured for this component and you need to define this for each component where the QApi service.
#Component({
selector: 'nav-bar',
template: `Test NavBar`,
providers: [QApi, UserService]
})
You also mix things. I mean you can put the UserService provider at the application level and QApi at the component level. In fact what is important is that Angular can find providers for all the involved elements in the processing chaining (with dependency injection). They can come from either component level (1st) or application level (2nd).
Hope that it gives you some additional hints following alexpods and MichaelOryl great answers ;-)
Thierry
List the services in your bootstrap call (wherever you are handling that). Something like the following should work:
bootstrap(App, [UserService, QApi, COMMON_DIRECTIVES, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, HTTP_PROVIDERS]);
providers// directives added here are available to all children
Then you will have a single instance of each of those services available to the rest of your application.

animations on angular-dart 0.11

OK, I'm on angular-dart 0.11.0, following the examples provided, applying the appropriate name changes and no joy. Here goes:
main.dart
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
import 'package:angular/animate/module.dart';
part 'package:myapp/src/my_ctrl.dart';
part 'package:myapp/src/my_dir.dart';
class MyModule extends Module {
MyModule() {
install(new AnimationModule());
bind(MyCtrl);
bind(MyDir);
}
}
main() {
applicationFactory()
.addModule(new MyModule())
.run();
}
main.css
.my-base-class.ng-enter {
transition: all 2s;
opacity: 0.000001; /* to avoid some chrome bug? */
}
.my-base-class.ng-enter.ng-enter-active {
opacity: 1.0;
}
index.html
<div ng-if="ctrl.bool" class="my-base-class">my stubbornly refusing to animate content</div>
the animation related classes ('ng-enter', etc) don't seem to get applied. Instead, i see an 'ng-binding' class. I suspect that the current code doesn't even activate the animation feature but i don't know how to fix it as there are no error messages.
thanks in advance
Sorted it out, there was nothing wrong with the animation setup. The problem was on how I was initiating the animation. I was expecting some data from an ajax call and, of course, angular-dart cannot handle this on its own, it needs to be told about the change through 'scope.watch'

Resources