Angular2加载子路由而不重新加载父级

时间:2016-08-30 19:22:04

标签: javascript angular angular-routing

我刚开始使用angular2并且遇到了问题。当当前视图是父路由时导航到子路由时,父路由仍会重新加载。

我的用户页面有此路由配置。

const userRoutes: Routes = [
    {
        path: ':username',
        component: UserProfileComponent,
        children: [
            {
                path: '',
                component: UserFeedComponent
            },
            {
                path: 'news',
                component: UserNewsComponent
            }
        ]
    },
];

export const userRouting = RouterModule.forChild(userRoutes);

user-profile.component:

@Component({
    selector: 'user-profile',
    templateUrl: 'app/+users/user-profile.component.html',
    styleUrls: ['app/+users/user-profile.component.css']
})
export class UserProfileComponent {
    constructor(private users: UserService, private route: ActivatedRoute, private titleService: TitleService) {
    }

    private user: User;
    private title: string;

    ngOnInit() {
        console.log("init");
        this.route.params.subscribe(params => {
            let username = params['username'];
            this.users.resolveUsername(username).subscribe(user => {
                this.user = user;
                this.users.user.next(user)
            });
        });

        // use the titleService to subscribe to a change in title. Child route handles title.
        this.titleService.title.subscribe(title => this.title = title)
    }
}

UserProfileComponent的模板:

<div class="profile-header grid-content medium-6 medium-offset-3 small-12" *ngIf="user">
    <img src="{{user?.picture}}" class="thumbnail avatar">
    <div class="profile-info">
        <h1>{{user?.name}}</h1>
        <h4><a [routerLink]="['/users', user.username]"  *ngIf="user"> @{{user.username}}</a></h4>
    </div>
    <ul class="menu-bar">
        <li><a [routerLink]="['/users', user.username]"  *ngIf="user"><i class="fa fa-rss"></i> Feed</a> </li>
        <li><a [routerLink]="['news']"><i class="fa fa-newspaper-o"></i> News</a> </li>
    </ul>
</div>

<h1>{{title}}</h1>
<hr>
<router-outlet></router-outlet>

因此,如果我在UserFeedComponenet并导航到UserNewsComponenet,则会重新加载整个UserProfileComponent。这会降低页面加载速度,因为用户通过HTTP请求再次加载到UserProfileComponent ngOnInit()

这是angular2的怪癖还是我做错了什么?如果是前者,那么我将为它创建一个问题。这样做效率非常低,但我很欣赏在某些情况下你可能需要但在这种情况下我不需要。

0 个答案:

没有答案