2

我正在使用 angular2-webpack-starter,因为 Route 在“2.0.0-rc.1”中还不是标准,所以他们使用@angular/route-depriated 进行路由。现在

这是我的服务

@Injectable()
export class JSTreeService {

  constructor(private http: Http) {

  }
  // Uses http.get() to load a single JSON file
  getData(): Observable<IDataItem[]> {
    return this.http.get('url')
      .map((res: Response) => res.json());

  }


}

这是我订阅服务并将其传递给另一个服务以将其传递给其他组件的主要组件

@Component({
  selector: 'app',
  pipes: [],
  providers: [JSTreeService, HTTP_PROVIDERS, SharedData],
  directives: [],
  encapsulation: ViewEncapsulation.None,

  template: `
    <header>
      <md-toolbar color="primary">
        <span>{{ name }}</span>
        <nav>
          <ul>
            <li router-active>
              <a [routerLink]=" ['Index'] ">Index</a>
            </li>
            |
            <li router-active>
              <a [routerLink]=" ['Home'] ">Home</a>
            </li>
            |
            <li router-active>
              <a [routerLink]=" ['About'] ">About</a>
            </li>
            |
            <li router-active>
              <a [routerLink]=" ['Items'] ">Items</a>
            </li>
          </ul>
        </nav>
      </md-toolbar>
    </header>
    <md-progress-bar mode="indeterminate" color="primary" *ngIf="loading"></md-progress-bar>

    <main>
      <router-outlet></router-outlet>
    </main>


})
@RouteConfig([
  { path: '/', name: 'Index', component: Home, useAsDefault: true },
  { path: '/home', name: 'Home', component: Home },


  { path: '/item', name: 'Items', component: ItemComponent },
  // Async load a component using Webpack's require with es6-promise-loader and webpack `require`
  { path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') }
])
export class App {

  dataItem: IDataItem[];

  // @Input() flag
  constructor(
    public appState: AppState,
    private _itemData: JSTreeService,
    private _sharedData: SharedData) {

  }
  getData() {
    this._itemData.getData()
      .subscribe(
      // the first argument is a function which runs on success
      (data: IDataItem[]) => {
        this.dataItem = data;
      },
      // the second argument is a function which runs on error
      err => console.error(err),
      // the third argument is a function which runs on completion
      () => (this._sharedData.dataItem = this.dataItem)

      );

    this.flag = 1;
  }

  ngOnInit() {
    console.log('Initial App State', this.appState.state);
    console.log('hello `Item` component');
    this.getData();
  }

}

这是我的路线组件

@Component({
  selector: 'Item',
  template: require('./item.html'),
  providers: [
  ]
})
export class ItemComponent  {
  dataItem: IDataItem[];
  flag: number;

  constructor(private _sharedData: SharedData) {

  }

  ngOnInit() {
    // console.log(this.dataItem);
    this.dataItem = this._sharedData.dataItem;

  }

  ngOnDestroy() {
    // this.dataItem = this._sharedData.dataItem;
  }
}

这是共享服务

@Injectable()
export class SharedData {
  constructor() {

  }
  dataItem:IDataItem[];


}

这是我的 item.template

<div class="">
  <label *ngFor="let item of dataItem"> <input type="checkbox" name="checkbox" value="value"> {{item.text}} <br></label>
</div>

我可以成功地将数据从 appcomponent 传递到“ItemComponent”。因此,每当我加载我的应用程序时,它都会订阅 http 调用并将数据传递给 SharedService。当我单击 Item 时,它会路由到 ItemComponent,它会显示数据。现在我的问题是每次我路由到 Item 时,每次它重新创建 ItemComponent 时我的数据都会消失。我不想要它。我想存储该组件的状态。这是在组件之间传递数据的好方法吗?我是 Angular2 的新手,任何形式的帮助都将不胜感激 :) 我更新的 ItemComponent :

@Component({
  selector: 'Item',
  template: require('./item.html'),
  providers: [
    // JSTreeService,

  ]
})
export class ItemComponent implements CanReuse, OnReuse {
  dataItem: IDataItem[];
  flag: number;

  constructor(private _sharedData: SharedData) {
    // this.dataItem = params.get('dataitems');


  }

  ngOnInit() {
    // console.log(this.dataItem);
    this.dataItem = this._sharedData.dataItem;

  }
  routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) {


    return true;
  }
  routerOnReuse(next: ComponentInstruction, prev: ComponentInstruction) {
    //  this.name = next.params['name'];
    this.dataItem = this._sharedData.dataItem;
    console.log(this.dataItem);
  }
  ngOnDestroy() {
    // this.dataItem = this._sharedData.dataItem;
  }
}

是的,我正在使用 webpackstarter 套件中的 @angular/router-depriated

4

1 回答 1

1

将数据保存在服务中,并在重新创建组件时从那里获取数据(当您使用此组件路由回路由时)

对于导航仅更改参数值的情况,您可以实现@CanReuse()并返回true,因此路由器在这种情况下不会释放和重新创建组件。

routerCanReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : boolean |
<boolean> {
  return true; 
}

这尚未在新RC.1路由器中实现。

于 2016-05-12T08:18:07.137 回答