Angular 2共享不同路由中组件之间的服务

时间:2017-04-24 16:32:51

标签: javascript angular typescript routing lazy-loading

我在Angular 2项目中有一个我不知道如何解决的行为。我正在使用带有Angular 2 2.3的webpack(如果这有帮助)。

我有一个复杂的项目,其结构如下:

- index.ts
- app.module.ts
- app.component.ts
- app.routes.ts
- services
     - login.service.ts
- +innerapp
     - inner.routes.ts
     - inner.module.ts
     - inner.component.ts
     - inner.component.html
     - services
         -inner.service.ts
     - insideinner
         - insideinner.component.ts
         - insideinner.component.html
         - header
             - header.component.ts
             - header.component.html
         - form
             - form.component.ts
             - form.component.html

执行show login然后路由到+ innerapp。 Inner.component.ts加载inner.services.ts并对数据进行http调用。从服务器移动了大量数据,并在inner.service.ts中初始化了一些BehaivorSubject。

一切正常,但用户点击按钮并加载一个大表单的form.component.ts。用户填写表单并单击提交,此时将调用inner.service来添加数据表单。令我惊讶的是inner.service没有数据,它刚刚初始化。

以下代码。

//inner.routes.ts
export const routes = [
  { path: '', children: [
  { path: '', component: InnerComponent },
  { path: 'form', component: FormComponent },
  ]},
];

inner.module.ts

import { routes } from './inner.routes';
import { InnerComponent } from './inner.component';
import { FormComponent } from './insideinner/form/form.component';

// Services
import { InnerService } from './service/inner.service';

@NgModule({
  declarations: [
    // Components / Directives/ Pipes
    InnerComponent,
    FormComponent
  ],
  imports: [
    RouterModule.forChild(routes),
  ],
  providers: [
    InnerService
  ]
})
export class InnerModule {
  public static routes = routes;
}

inner.component.ts:

@Component({
  selector: 'inner',
  templateUrl: './inner.component.html'
})
export class InnerComponent implements OnInit {

  constructor ( private innerService: innerService ) {

    this.innerService.fetchData()
      .subscribe(
        (response) => {
          this.innerService.addData(response.json());
        },
    (error) => {
      alert(error);
    }
  );

}

服务/ inner.services.ts

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { Headers, RequestOptions, Http, Response } from '@angular/http';

@Injectable()
export class InnerService {

  // Observable string streams
  public readonly data: Observable<string>;

  // Observable string sources
  private _data: BehaviorSubject<string> = new BehaviorSubject(null);

  // private properties
  private options: RequestOptions;

  constructor( public http: Http ) {
    this.data = this._user.asObservable();

    // http standard values
    let token = localStorage.getItem('token');
    let cabs = new Headers({ Authorization: 'Bearer ' + token });
    this.options = new RequestOptions({ headers: cabs });
  }

  // Service message commands
  public addData (t: string) {
    this._data.next(t);
  }

  public saveData(t: string) {

    return this.http.post(blabla,
      {
        data: t
      },
      this.options
    ).map((res: Response) => {
      this.addData(t);
      return true;
    }).catch(this.handleError);

  }

  private handleError (error: any) {
    //code
  }

  public fetchData(): Observable<any> {
    return this.http.get(blabla, this.options)
      .map((res) => { return res.body })
      .catch(this.handleError);
  }
}

insideinner /形式/ form.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

// services & others
import { InnerService } from '../../services/inner.service';

@Component({
  selector: 'add-members',
  templateUrl: './form.component.html',
  encapsulation: ViewEncapsulation.None
})
export class FormComponent implements OnInit  {

  constructor(
    private fb: FormBuilder,
    private innerService: InnerService
  ) {}

  public ngOnInit() {
    this.showForm = false;
  }

  public onSubmit(value: string) {

    this.innerService.saveData(value); //Fail here, inner service are without data 
  }

  public showAdd() {
    this.showForm = true;
  }
}

我阅读了很多文档并在这里阅读了类似的问题,但解决方案并不适用于我。

编辑2017-05-31 我认为那是愚蠢的问题。我发现这个问题与路由中的lazyload有关。我尝试这个解决方案: Angular 2 lazy loaded module - service not singleton

和这个解决方案: Angular 2 How to make singleton service available to lazy loaded modules

但没有人为我工作。我想说这个项目很垃圾,我又开始使用Angular 1.6,但我真的很想解决这个问题,以便制定未来的项目。

0 个答案:

没有答案