相同组件之间的角度4动画

时间:2017-08-28 14:59:16

标签: angular

我对具有相同组件路径的动画有问题。例如。我有这条路线:

  

{路径:'产品/类别/:类别',组件:CategoryComponent},

首先,我解决了路径参数的问题,因为当我在同一个组件之间导航时,它们不刷新ngOnit()函数。但是现在我已经添加了动画到我的应用程序,并且如果我从HomeComponent转到CategoryComponent,则效果很好。但是,如果我使用不同的参数从CategoryComponent转到CategoryComponent,动画就不起作用了。

这是我的动画文件:

import { animate, AnimationEntryMetadata, state, style, transition, trigger } from '@angular/core';

// Component transition animations
export const slideInDownAnimation: AnimationEntryMetadata =
  trigger('routeAnimation', [
    state('*',
      style({
        opacity: 1,
        transform: 'translateX(0)'
      })
    ),
    transition(':enter', [
      style({
        opacity: 0,
        transform: 'translateX(-100%)'
      }),
      animate('0.5s ease-in')
    ]),
    transition(':leave', [
      animate('0.5s ease-out', style({
        opacity: 0,
        transform: 'translateY(100%)'
      }))
    ])
  ]);

这里是我的CategoryComponent.ts

import { Component, OnInit, EventEmitter,Input, Output,HostBinding} from '@angular/core';
import { Pipe, PipeTransform } from '@angular/core';

import {FirebaseService} from '../../services/firebase.service';
import { AngularFireDatabase, FirebaseListObservable,FirebaseObjectObservable} from 'angularfire2/database';
import {Router, ActivatedRoute, Params,ParamMap} from '@angular/router';
import * as firebase from 'firebase';
import { Observable } from 'rxjs';
import {Subject} from 'rxjs';
import { routerTransition } from '../../router.animations';
import { slideInDownAnimation } from '../../animations';

import { FlashMessagesService } from 'angular2-flash-messages';
@Component({   
  host: {
     '[@routeAnimation]': 'true'
   },
  selector: 'app-category',
  templateUrl: './category.component.html',  
  styleUrls: ['./category.component.css'],  
  animations: [ slideInDownAnimation ]
})
export class CategoryComponent implements OnInit {
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display')   display = 'block';
  @HostBinding('style.position')  position = 'absolute';
  products:any;
  search:any;
  imageUrls:any = [];
  imgSelected: any;
  counter:any;
  image:any;
  images:any;
  myimage:any;
  count:any;
  sub:any;  
  i:any;
  category:any;
  fakeimage:any;  
  constructor(
    private firebaseService: FirebaseService,
    private router:Router,
    public af:AngularFireDatabase,
    private route:ActivatedRoute,    
    private flashMessage:FlashMessagesService) {


  }

ngOnInit() {

    this.counter = 0; 

    var params;
    this.sub = this.route.paramMap
      .switchMap((params: ParamMap) =>
      this.firebaseService.getProductsByCategory(params.get('category'))).subscribe(products => {
      this.products = products;
      this.count = products.length;
    });;


 }

  returnImage(key,url){
   this.imageUrls.push(new ImageUrl(key,url));
  }
  searchProps(){    
    this.firebaseService.getProductsByTitle(this.search.toLowerCase()).subscribe(products => { 
      this.products = products;
    });
  }

getProductsByTitle(title){
  console.log('here');    
    this.firebaseService.getProductsByTitle(title.toLowerCase()).subscribe(products => { 
      this.products = products;
    }); 

}
getImageUrl(prodid) {
        // Go call api to get poster.  
        var data = ''; 
        var that = this;
        this.firebaseService.getProductImages(prodid).subscribe(images => { 
          this.image = images[0];
          var img = this.image;
          if(this.image != null){
            let storageRef = firebase.storage().ref();
            let spaceRef = storageRef.child(this.image.path);
            storageRef.child(img.path).getDownloadURL().then(function(url) {
              that.returnImage(img.$key,url);

              }).catch(function(error) {
                // Handle any errors
              });
          }             
        });
}
  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}
export class ImageUrl {
  url: string;
  id:string;
  constructor(public _id:string,public _url: string) {

  }
}

知道我能在这做什么吗?

感谢。

2 个答案:

答案 0 :(得分:3)

你击中了头部的钉子。当从路由参数转到使用相同组件的另一个路由参数时,ngOnInit不会再次触发;只有内容被换掉。

路由器设计为以这种方式工作,即使路由参数发生变化也要使用相同的组件实例。

Github(https://github.com/angular/angular/issues/17349)上有一个话题可以讨论这个问题。来自Matsko的Plunker在该帖子上显示了一个应用程序的工作版本,该应用程序使用自定义RouteReuseStrategy来强制重新加载组件。

答案 1 :(得分:3)

您可以添加如下路线重用策略:

import { ActivatedRouteSnapshot, RouteReuseStrategy, DetachedRouteHandle } from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return false;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): boolean {
        return false;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return false;        
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        return false;
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return false;
    }    
}

然后将其作为提供者导入您的模块:

providers: [
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
],

这将导致ngOnInit在每个路径参数更改时触发。在我的应用程序中,我将此策略用作页面转换的一部分。我写了一篇关于如何在https://wpwebapps.com/angular-5-router-animations-tied-to-images-loading/

处设置的帖子