2017-02-17 2 views
2

stackoverflow에서 많이 검색했지만 내 문제에 대한 실질적인 설명을 찾지 못했습니다 .... RouterModule을 사용하여 간단한 angular2 응용 프로그램을 만들려고합니다. , 간단한 서비스 및 간단한 구성 요소. 그래서 :
내 라우터 모듈 :각도 2 탐색 다시 모든 서비스 및 구성 요소를 초기화합니다.

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>, 이것은 컴포넌트 및 ser에 작성한 console.log를 트리거합니다. 부 생성자 ..., 내가 탐색 할 때마다 콘솔에 'component reinit'및 'reinit service'가 표시됩니다. 어떻게 피할 수 있습니까? 감사합니다

+1

http://stackoverflow.com/questions/33940095/angular2-routing-keeping-state-of-component-when-route-changes/36010817#36010817에 설명 된대로 맞춤 재사용 전략을 구현할 수 있습니다. 일반적으로 더 나은 접근 방법은 구성 요소를 어떤 방식으로 빌드하는 것입니다. 멀리 탐색 할 때 파괴 된 시점과 뒤로 탐색 할 때 다시 작성한 시점은 중요하지 않습니다. 예를 들어 구성 요소 자체가 아닌 공유 서비스에 상태를 저장할 수 있습니다. –

+0

나는 내 서비스의 사유지에 학생들을 저장하고 싶었지만, 이것이 싱글 톤이 아닌 것처럼 다시 초기화되었다 ... 이것이 각도의 진정한 기능이라고 말하는가? /? ... –

+0

서비스를 구성 요소에 제공하면 구성 요소를 사용하여 서비스가 만들어지고 소멸됩니다. 당신의 유스 케이스의 경우 부모 컴포넌트에서 제공되어야한다. (컴포넌트가 추가 된 곳의''을 포함하거나'@NgModule()'에 제공해야한다. 전체 응용 프로그램을 만들고 응용 프로그램을 사용하여 만들었습니다. –

답변

2

문제는 여기에 있습니다 : 구성 요소 자체에 공급자를로드했지만 전체 모듈에서 사용할 수 있도록 내 NgModule에만 선언되어야합니다.

providers: [ StudentService ] 

을하고는 서비스가 된 이유가 구성 요소 ... 감사라고 할 때마다 다시 instancied이다 :이 같은 구성 요소의 프로 바이더를 선언-다시했다!

관련 문제