我是Angular 2的新手,我为社交登录做了代码运行良好,但我收到了这个错误:Uncaught Type Error: Cannot read property Injectable of undefined
,我试图解决但失败了,需要帮助。先谢谢你!
login.component.html
<button type="button" class="btn btn-danger" (click)="signIn('google')" id="googleBtn"><i class="ion-logo-google"></i> Google</button>
login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { ValidationService } from 'app/services/validation.service';
import { AuthServiceLogin } from './../../services/authservice';
import { Router } from '@angular/router';
import { AuthService } from "angular2-social-login";
declare var $: any;
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [AuthServiceLogin, AuthService]
})
export class LoginComponent {
error: string;
loading: boolean = false;
success: string;
errorReg: string;
successReg: string;
successForgPass: string;
errorForgPass: string;
public user;
sub: any;
public registerForm;
public userForm;
public passForm;
ngOnInit() {
this.registerFormInit();
this.userFormInit();
this.passFormInit();
}
constructor(public _auth: AuthService, private formBuilder: FormBuilder, private service: AuthServiceLogin, private router: Router) {}
registerFormInit() {
this.registerForm = this.formBuilder.group({
'name': ['', [Validators.required]],
'username': ['', [Validators.required, ValidationService.usernameValidator]],
'email': ['', [Validators.required, ValidationService.emailValidator]],
'password': ['', [Validators.required, ValidationService.passwordValidator]]
});
}
userFormInit() {
this.userForm = this.formBuilder.group({
'email': ['', [Validators.required, ValidationService.emailValidator]],
'password': ['', [Validators.required]]
});
}
passFormInit() {
this.passForm = this.formBuilder.group({
'email': ['', [Validators.required, ValidationService.emailValidator]]
});
}
// ----------- Social Login -----------//
signIn(provider) {
this._auth.login(provider).subscribe(
(data)=>{
alert("login() calling !");
this.user = data;
this.sociallogin(data)
console.log(data);
}
);
}
sociallogin(data){
this.service.sociallogin(data).subscribe(
data =>{
alert(" sociallogin() called Successfully ! with token ");
localStorage.setItem('id_token', data.token);
this.router.navigateByUrl('/dashboard');
},
error =>{
console.log("User data in sociallogin()"+this.user);
this.error = "Invalid google Sign in !";
}
)
}
// -----------#End Social Login -----------//
// ----------- Simple Login -----------//
loginUser(credential) {
this.loading = true;
this.error = "";
this.service.loginfn(this.userForm.value).subscribe(
data => {
if (data.token) {
this.userFormInit();
$('#myModal').modal('hide');
localStorage.setItem('id_token', data.token);
this.router.navigateByUrl('/dashboard');
this.loading = false;
} else {
// this.userFormInit();
window.scrollTo(0, 0);
this.error = data.msg;
}
},
error => {
this.userFormInit();
window.scrollTo(0, 0);
this.error = "Invalid username or password !";
this.loading = false;
}
);
}
// -----------#End Simple Login -----------//
// ----------- Register User -----------//
registerUser(credential) {
this.loading = true;
this.errorReg = "";
this.successReg = "";
this.service.addUser(this.registerForm.value).subscribe(
data => {
if (data.success) {
this.registerFormInit();
window.scrollTo(0, 0);
this.successReg = data.msg;
} else {
this.passFormInit();
window.scrollTo(0, 0);
this.errorReg = data.msg;
}
this.loading = false;
},
error => {
this.passFormInit();
window.scrollTo(0, 0);
this.errorReg = error.msg;
this.loading = false;
}
);
}
// -----------#End Register User -----------//
forgetPass(event) {
event.preventDefault();
if (this.passForm.valid) {
this.service.forgotPassword(this.passForm.value).subscribe(
data => {
if (data.success) {
this.passFormInit();
window.scrollTo(0, 0);
this.successForgPass = data.msg;
} else {
//this.passFormInit()
window.scrollTo(0, 0);
this.errorForgPass = data.msg;
}
this.loading = false;
},
error => {
this.passFormInit();
window.scrollTo(0, 0);
this.error = error.msg;
this.loading = false;
}
);
}
}
}
authservice.ts
import { ControlMessageComponent } from './../home/control-message/control-message.component';
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { tokenNotExpired } from 'angular2-jwt';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
@Injectable()
export class AuthServiceLogin {
private getHeaders() {
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Access-Control-Allow-Credentials", "true");
headers.append("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
headers.append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Request-Method, Access-Control-Request-Headers");
return headers;
}
constructor(private http: Http, private router: Router) { }
loginfn(credentials) {
return this.http.post(environment.API_URL+'/public/api/login', credentials, { headers: this.getHeaders() }).map(res => res.json());
}
addUser(data) {
return this.http.post(environment.API_URL+'/public/api/register', data, { headers: this.getHeaders() }).map(res => res.json());
}
forgotPassword(data) {
return this.http.post(environment.API_URL+'/public/api/forget', data, { headers: this.getHeaders() }).map(res => res.json());
}
activateUser(userId) {
let url = environment.API_URL+"/public/api/activation/" + userId;
return this.http.get(url, { headers: this.getHeaders() }).map(res => res.json());
}
changePassword(code, formdata) {
let url = environment.API_URL+"/public/api/resetpassword/" + code;
return this.http.post(url, formdata, { headers: this.getHeaders() }).map(res => res.json());
}
loggedIn() {
return tokenNotExpired();
}
logout() {
localStorage.removeItem('id_token');
this.router.navigateByUrl('/home');
}
sociallogin(data) {
return this.http.post(environment.API_URL+'/public/api/sociallogin', data, { headers: this.getHeaders() }).map(res => res.json());
}
}
app.module.ts
import { HttpModule, Http, RequestOptions } from '@angular/http';
import { provideAuth, AuthHttp, AuthConfig } from 'angular2-jwt';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { TooltipModule, ModalModule, AlertModule, BsDropdownModule } from 'ng2-bootstrap';
import { AppRoutesModule, routesComponents } from './app.routes';
import { FileUploadModule } from 'ng2-file-upload';
import { AuthServiceLogin } from './services/authservice';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './home/header/header.component';
import { BannerComponent } from './home/banner/banner.component';
import { ProcessComponent } from './home/process/process.component';
import { FeaturesComponent } from './home/features/features.component';
import { PricingComponent } from './home/pricing/pricing.component';
import { FaqComponent } from './home/faq/faq.component';
import { FooterComponent } from './home/footer/footer.component';
import { TestimonialsComponent } from './home/testimonials/testimonials.component';
import { LoginComponent } from './home/login/login.component';
import { AuthGuard } from './services/auth-guard.service';
import { ControlMessageComponent } from './home/control-message/control-message.component';
import { ValidationService } from 'app/services/validation.service';
import { ProfileComponent } from './shared/profile/profile.component';
import { InlineEditorModule } from 'ng2-inline-editor';
import { MaterialModule } from '@angular/material';
import 'hammerjs';
import { HeaderCoreComponent } from './shared/header-core/header-core.component';
import { FooterCoreComponent } from './shared/footer-core/footer-core.component';
import { DashboardComponent } from './shared/dashboard/dashboard.component';
import { ResumeComponent } from './shared/resume/resume.component';
import { TemplatesComponent } from './shared/templates/templates.component';
import { MyDatePickerModule } from 'mydatepicker';
import { SocialProfileComponent } from './shared/resume/social-profile/social-profile.component';
import { WorkExperienceComponent } from './shared/resume/work-experience/work-experience.component';
import { EducationComponent } from './shared/resume/education/education.component';
import { SkillsComponent } from'./shared/resume/skills/skills.component';
import { LanguagesComponent } from './shared/resume/languages/languages.component';
import { InterestsComponent } from './shared/resume/interests/interests.component';
import { ReferencesComponent } from './shared/resume/references/references.component';
import { VolunteerComponent } from './shared/resume/volunteer/volunteer.component';
import { AwardsComponent} from './shared/resume/awards/awards.component';
import { PublicationsComponent } from './shared/resume/publications/publications.component';
import { ButtonsComponent } from './shared/buttons/buttons.component';
import { SanitizeHtmlPipe } from './pipe/sanitize-html.pipe';
import { ShareComponent } from './share/share.component';
import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';
import { Angular2SocialLoginModule } from "angular2-social-login";
let providers = {
"facebook": {
"clientId": "1850828045172034",
"apiVersion": "v2.8"
},
"google":{
"clientId": "1005948066107-mp4f1rluvsdog2gu89ho89sjncf1lhek.apps.googleusercontent.com"
},
"linkedin": {
"clientId": "810ngkn1q263bi"
}
};
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({}), http, options);
}
@NgModule({
declarations: [
AppComponent,
routesComponents,
HomeComponent,
HeaderComponent,
BannerComponent,
ProcessComponent,
FeaturesComponent,
PricingComponent,
FaqComponent,
FooterComponent,
TestimonialsComponent,
LoginComponent,
ControlMessageComponent,
DashboardComponent,
ResumeComponent,
ProfileComponent,
HeaderCoreComponent,
FooterCoreComponent,
SocialProfileComponent,
WorkExperienceComponent,
EducationComponent,
SkillsComponent,
LanguagesComponent,
InterestsComponent,
ReferencesComponent,
VolunteerComponent,
AwardsComponent,
PublicationsComponent,
ButtonsComponent,
TemplatesComponent,
SanitizeHtmlPipe,
ShareComponent,
PagenotfoundComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutesModule,
ReactiveFormsModule,
InlineEditorModule,
MaterialModule.forRoot(),
TooltipModule.forRoot(),
ModalModule.forRoot(),
AlertModule.forRoot(),
BsDropdownModule.forRoot(),
FileUploadModule,
MyDatePickerModule ,
Angular2SocialLoginModule
],
providers:
[
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
},
ValidationService,
AuthServiceLogin,
AuthGuard
],
bootstrap: [AppComponent]
})
export class AppModule { }
Angular2SocialLoginModule.loadProvidersScripts(providers);