Angular4依赖注入:我做错了什么?

时间:2017-10-17 13:15:07

标签: angular visual-studio

我几乎是一名后端开发人员,但我正在努力让自己熟悉Angular,所以如果我在这里听起来非常无知,请耐心等待。

我使用.NET Core 2.0后端API通过Visual Studio 2017创建了SPA。它为Angular实现设置了一个基本的文件结构,所以我继续使用它。 (这可能是我的第一个错误)

在/ app / services中,我创建了一个名为authentication.service的服务,其中authentication.service.ts文件如下所示:

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthenticationService {
    public token: string;

    constructor(private http: Http) {
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;
    }

    login(username: string, password: string): Observable<boolean> {
        return this.http.post('/api/authentication/login', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {
                return this.updateStorage(response, username);
            });
    }

    logout(): void {
        this.token = null;
        localStorage.removeItem('currentUser');
    }

    refresh(username: string): Observable<boolean> {
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        var refreshToken = currentUser && currentUser.refreshToken;
        return this.http.post('/api/authentication/refresh',
            JSON.stringify({ username: username, refreshToken: refreshToken }))
            .map((response: Response) => {
                return this.updateStorage(response, username);
            });
    }

    register(username: string, email: string, password: string): Observable<boolean> {
        return this.http.post('/api/authentication/register',
                JSON.stringify({ username: username, email: email, password: password }))
            .map((response: Response) => {
                return (response.status === 200);
            });
    }

    private updateStorage(response: Response, username: string): boolean {
        let token = response.json() && response.json().token;
        if (token) {
            this.token = token;
            let refreshToken = response.json().refreshToken;
            localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token, refreshToken: refreshToken }));
            return true;
        } else {
            return false;
        }
    }
}

...然后,我在/app/components/login创建了一个名为login.component.ts的组件,我几乎无耻地复制并粘贴在一个在线示例中:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import Authenticationservice = require('../../services/authentication.service');
import AuthenticationService = Authenticationservice.AuthenticationService;

@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService) { }

    ngOnInit() {
        // reset login status
        this.authenticationService.logout();

        // get return url from route parameters or default to '/'
        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
                data => {
                    this.router.navigate([this.returnUrl]);
                },
                error => {
                    //this.alertService.error(error);
                    this.loading = false;
                });
    }
}

...继续我无耻的副本&amp;粘贴方式,我创建了login.component.html文件,如下所示:

<div class="col-md-6 col-md-offset-3">
    <h2>Login</h2>
    <form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
            <label for="username">Username</label>
            <input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required />
            <div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div>
        </div>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
            <label for="password">Password</label>
            <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required />
            <div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div>
        </div>
        <div class="form-group">
            <button [disabled]="loading" class="btn btn-primary">Login</button>
            <img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
            <a [routerLink]="['/register']" class="btn btn-link">Register</a>
        </div>
    </form>
</div>

现在,我尝试在app.module.shared.ts文件中注册我的服务:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { LoginComponent } from './components/login/login.component';
import { AuthenticationService } from './services/authentication.service';

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        LoginComponent
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'login', component: LoginComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [
        AuthenticationService
        ]
})
export class AppModuleShared {
}

...然后我试图运行它,但是立刻,我收到了一个例外:

An unhandled exception occurred while processing the request.

NodeInvocationException: Prerendering failed because of error: ReferenceError: Authenticationservice is not defined
at Object.<anonymous> (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:16331:50)
at __webpack_require__ (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:16147:93)
at __webpack_require__ (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:20:30)
at Object.hasOwn (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:14208:77)
at __webpack_require__ (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:20:30)
at Object.<anonymous> (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:16422:81)
at __webpack_require__ (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:20:30)
at D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:66:18
at Object.<anonymous> (D:\CoreExchange\AngularExperiments\Experiment01\Experiment01\ClientApp\dist\main-server.js:69:10)
Current directory is: D:\CoreExchange\AngularExperiments\Experiment01\Experiment01

我想也许我必须在app.module.browser.tsapp.module.server.ts文件中注册该服务,所以我尝试了,但它似乎没有什么区别。

显然,我错过了一个重要的步骤,但我不知道它是什么,并且错误消息不是很有帮助。有人能告诉我在哪里/如何搞砸了我的服务?

1 个答案:

答案 0 :(得分:1)

在login.component.ts中,您的import语句会出现一些问题:

您可以直接导入AuthenticationService,如下所示:

从&#39; ./ authentication.service&#39;;

导入{AuthenticationService}

PS:看起来您使用的是Authenticationservice而不是AuthenticationService