我在stackoverflow中搜索了很多但我没有找到对我的问题的真正解释....
我正在尝试使用RouterModule,一个简单的Service和一个简单的Component来创建一个简单的angular2应用程序。
所以:
我的路由器模块:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { StudentListComponent } from '../students-list.component';
import { StudentComponent } from '../student.component';
const routes: Routes = [
{ path: 'students', component : StudentListComponent },
{ path: 'student/:id', component: StudentComponent },
{ path: '**', redirectTo : '/students', pathMatch: 'full' },
{ path: '', redirectTo : '/students', pathMatch: 'full' }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRouterModule { }
我的组件:
import { Component, OnInit } from '@angular/core';
import { StudentService } from './services/student.service';
import { Student } from './class/Student';
@Component({
selector: 'student-list',
templateUrl: 'app/views/students-list.component.html',
styleUrls: ['app/views/styles/students-list.component.css'],
providers : [ StudentService ]
})
export class StudentListComponent implements OnInit {
private studentService: StudentService;
students: Student[];
constructor(studentService: StudentService) { console.log('reinit component');
this.studentService = studentService;
}
ngOnInit(): void {
if(!this.students)
this.studentService.getStudents().then( (students) => this.students = students );
}
}
我的服务:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Student } from '../class/Student';
import { Note } from '../class/Note';
import { CourseService } from './course.service';
@Injectable()
export class StudentService {
static service: StudentService;
private httpUrl = "http://localhost/NotesApp/webServ/";
private students: Student[];
private courseService: CourseService;
private http:Http;
constructor(courseService: CourseService, http:Http){ console.log('reinit service');
this.courseService = courseService;
this.http = http;
}
getStudents(): Promise<Student[]> {
return this .http
.get(this.httpUrl+'getStudents')
.toPromise()
.then( response => this.hydratedStudentArray( response.json() ) )
.catch( this.handleError );
}
getStudentById(id: number): Promise<Student> {
return this .http
.get(this.httpUrl+'getStudent/'+id)
.toPromise()
.then(response => this.hydratedStudent( response.json()[0]) )
.catch( this.handleError );
}
private hydratedStudentArray(jsonArray: { id: number, firstname: string, lastname: string }[]): Student[]{
let hydratedArray: Student[] = [];
for (let jsonElement of jsonArray){
hydratedArray.push(new Student(jsonElement.id, jsonElement.lastname, jsonElement.firstname));
}
return hydratedArray;
}
private hydratedStudent(jsonElement: { id: number, firstname: string, lastname: string }): Student{
return new Student(jsonElement.id, jsonElement.lastname, jsonElement.firstname);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
所以我的问题是:当我使用类似的链接导航时
<a routerLink="/students">Students</a>
或<a [routerLink]="['/student', student.id]" >{{ student.lastname }} {{ student.firstname }}</a>
,这会触发我在组件和服务构造函数中编写的console.log ......每次导航时,我都会在控制台中看到“重新启动组件”和“重新启动服务”。 ..我怎么能避免这个?
感谢
答案 0 :(得分:2)
问题在于:我在组件本身中加载了提供程序,但它应该仅在我的NgModule中声明,因此整个模块可以使用它。我在组件中重新声明了这样的提供程序:
providers: [ StudentService ]
这就是为什么每次调用组件时都重新安装服务的原因...... 谢谢!