【问题标题】:Angular 2 navigation re initialize all services and componentsAngular 2 导航重新初始化所有服务和组件
【发布时间】:2017-07-07 05:22:19
【问题描述】:

我在 stackoverflow 中搜索了很多,但我没有找到对我的问题的真正解释.... 我正在尝试使用 RouterModule、简单的服务和简单​​的组件制作一个简单的 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);
  }

}

所以我的问题是:当我使用类似的链接导航时 &lt;a routerLink="/students"&gt;Students&lt;/a&gt;&lt;a [routerLink]="['/student', student.id]" &gt;{{ student.lastname }} {{ student.firstname }}&lt;/a&gt;,这会触发我在组件和服务构造函数中编写的 console.log...,每次导航时我都会在控制台中看到“重新初始化组件”和“重新初始化服务”...我避免这个? 谢谢

【问题讨论】:

  • 您可以实现自定义重用策略,如stackoverflow.com/questions/33940095/… 中提到的。通常更好的方法是以某种方式构建组件,当它们在导航离开时被销毁并在导航返回时重新创建并不重要。例如,您可以将状态存储在共享服务中,而不是组件本身。
  • 我想在我的服务中将学生存储在一个私有属性中,但是最后一个也重新初始化,就像它不是单例一样......你是说这是 angular 的真正功能: / ? ...
  • 如果你在一个组件上提供服务,它会随组件一起创建和销毁。对于您的用例,它应该在父组件中提供(然后包含添加组件的&lt;router-outlet&gt;,或者在@NgModule() 中提供它,那么它将是整个应用程序的单例,并使用创建和销毁应用程序。

标签: angular service constructor components router


【解决方案1】:

问题出在这里:我在组件本身中加载了提供程序,但它应该只在我的 NgModule 中声明,所以整个模块都可以使用它。我正在像这样在组件中重新声明提供者:

providers:    [ StudentService ]

这就是为什么每次我调用该组件时都会重新实例化服务... 谢谢!

【讨论】:

    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多