我的angular 2应用程序需要很长时间才能为首次使用的用户加载,我需要帮助才能加快速度

时间:2016-02-07 13:13:17

标签: typescript angular

下面我已经粘贴在我的app.ts文件中。

我使用angular2,使用firebase和typescript。

原因是因为我有很多路线并且我注入了大量文件,所以它很慢吗?

此外,我的应用程序正常工作只是第一次访问主页的用户我有这个问题。

我不确定是否可以在底部改进引导程序,或者我是否做错了。

这是我的app.ts文件:

import {Component, bind, provide, Injectable} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser'
import {NgIf} from 'angular2/common';
import {Router, Location, ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF, CanActivate, OnActivate,
    ComponentInstruction} from 'angular2/router';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';
import {ANGULAR2_GOOGLE_MAPS_PROVIDERS} from 'angular2-google-maps/core';
import {enableProdMode} from 'angular2/core';
enableProdMode();

import {LoggedInRouterOutlet} from './interceptor';

import {AuthService} from './services/authService/authService';
import {SocialService} from './services/socialService/socialService';
import {UserService} from './services/userService/userService';
import {OrganisationService} from './services/organisationService/organisationService';
import {NotificationService} from './services/notificationService/notificationService';
import {EmailService} from './services/emailService/emailService';

import {UserProfile} from './models/profile/profile';
import {Organisation} from './models/organisation/organisation';

import {HeaderNavigation} from './components/header/header';
import {HeaderNavigationLoggedIn} from './components/header/headerNavigationLoggedIn';
import {HeaderNavigationLoggedInCompany} from './components/header/headerNavigationLoggedInCompany';
import {Footer} from './components/footer/footer';
import {SideMenuCompany} from './components/header/sideMenuCompany';
import {SideMenuUser} from './components/header/sideMenuUser';
import {Splash} from './components/splash/splash';

import {CreateJob} from './components/createJob/createJob';
import {SearchJobs} from './components/searchJobs/searchJobs';
import {Login} from './components/login/login';
import {Applications} from './components/applications/applications';
import {Register} from './components/register/register';
import {ForgotPassword} from './components/forgotpassword/forgotpassword';
import {ChangePassword} from './components/changepassword/changepassword';
import {ChangeEmail} from './components/changeemail/changeemail';
import {SocialRegister} from './components/socialregister/socialregister';
import {Admin} from './components/admin/admin';
import {Contact} from './components/contact/contact';
import {SearchUsers} from './components/searchusers/searchusers';

import {Jobs} from './components/job/jobs';
import {CompanyProfile} from './components/company/company';
import {Home} from './components/home/home';
import {Dashboard} from './components/dashboard/dashboard';
import {Profile} from './components/profile/profile';
import {UserApplications} from './components/userApplications/userApplications';

@Component({
    selector: 'app',
    providers: [UserService, UserProfile, OrganisationService, Organisation],
    template: `

        <Splash *ngIf="isLoggedIn"></Splash>    

        <HeaderNavigation *ngIf="!isLoggedIn"></HeaderNavigation>       

        <HeaderNavigationLoggedIn *ngIf="isLoggedIn && isUserLogin"></HeaderNavigationLoggedIn>
        <HeaderNavigationLoggedInCompany *ngIf="isLoggedIn && isCompanyLogin"></HeaderNavigationLoggedInCompany>

        <SideMenuCompany *ngIf="isLoggedIn && isCompanyLogin"></SideMenuCompany>
        <SideMenuUser *ngIf="isLoggedIn && isUserLogin"></SideMenuUser>

        <div class="content">
            <router-outlet></router-outlet> 
        </div>     
    `,
    directives: [RouterOutlet, RouterLink, Splash, HeaderNavigation, HeaderNavigationLoggedIn, NgIf, HeaderNavigationLoggedInCompany, SideMenuCompany, SideMenuUser, Footer, LoggedInRouterOutlet]
})

@RouteConfig([
    { path: '/', component: Home, as: 'Home', data:{title: 'Welcome Home'}},
    { path: '/home', component: Home, as: 'Home', useAsDefault: true},
    { path: '/login', component: Login, as: 'Login' },  
    { path: '/register/:id', component: Register, as: 'Register' },
    { path: '/forgotpassword', component: ForgotPassword, as: 'ForgotPassword' },
    { path: '/dashboard', component: Dashboard, as: 'Dashboard' },
    { path: '/search', component: SearchJobs, as: 'Search' },   
    { path: '/profile', component: Profile, as: 'Profile' },
    { path: '/settings', component: CompanyProfile, as: 'Settings' },
    { path: '/jobs', component: Jobs, as: 'Jobs' },
    { path: '/password', component: ChangePassword, as: 'Password' },
    { path: '/email', component: ChangeEmail, as: 'Email' },
    { path: '/applications', component: Applications, as: 'Applications' },
    { path: '/socialRegister/:id', component: SocialRegister, as: 'SocialRegister' },
    { path: '/socialRegister', component: SocialRegister, as: 'SocialRegister' },
    { path: '/applys', component: UserApplications, as: 'Applys' },
    { path: '/contact', component: Contact, as: 'Contact' },
    { path: '/searchTeachers', component: SearchUsers, as: 'SearchUsers' },
    { path: '/createJob', component: CreateJob, as: 'CreateJob' },
    { path: '/adminmarkchris2016', component: Admin, as: 'AdminMarkChris2016' },

    { path:'/**', redirectTo: ['Home']}
])

@Injectable()

export class AppComponent {
    router: Router;
    location: Location;
    authService: AuthService;
    userService: UserService
    isLoggedIn: boolean = false;
    isCompanyLogin: boolean = false;
    isUserLogin: boolean = false;
    userProfile: UserProfile;   

    constructor(_router: Router, _location: Location, _authService: AuthService, _userService: UserService, _userProfile: UserProfile){ 
        this.router = _router;
        this.location = _location;
        this.authService = _authService;
        this.userService = _userService;
        this.userProfile = _userProfile;

        this.isUserLoggedIn(this.location.path());

        //On refresh
        this.router.subscribe((currentRoute) => {
            this.isUserLoggedIn(currentRoute);
        })  
    }

    isUserLoggedIn(currentRoute): void{ 
        this.authService.checkIfLoggedIn().then((response) => { 
            this.isLoggedIn = response

            if(this.isLoggedIn){
                this.isUserOrganisationOrTeacher();                 
            }   

            if(currentRoute.substring(0, 14) == "socialRegister" || currentRoute == "socialRegister" || currentRoute == "home" || currentRoute == "contact" || currentRoute == "" || currentRoute == "forgotpassword" || currentRoute == "login" || currentRoute.substring(0, 8) == "register"){
                this.isCompanyLogin = false;
                this.isUserLogin = false;
                this.isLoggedIn = false;
            }           
        });  
    }

    isUserOrganisationOrTeacher(): void{
        this.userService.checkIfProfileExists().then((response) => {
            this.isCompanyLogin = false;
            this.isUserLogin = false;       

            if(response){
                this.isUserLogin = true;
                this.isCompanyLogin = false;
            }else{
                this.isCompanyLogin = true; 
                this.isUserLogin = false;                   
            }
        }); 
    }       
}

bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'}), HTTP_PROVIDERS, AuthService, SocialService, UserService, EmailService, OrganisationService, NotificationService, ANGULAR2_GOOGLE_MAPS_PROVIDERS]);

6 个答案:

答案 0 :(得分:17)

要准备好生产(并加快速度),你需要打包它。

我的意思是将所有文件转换为JavaScript文件,并以与Angular2相同的方式连接它们。这样,您将在单个JS文件中包含多个模块。这样,您将减少将应用程序代码加载到浏览器中的HTTP调用次数。

事实上,对于SystemJS的以下配置,每个模块只需一次调用(它适合开发但在生产中效率不高):

<script>
  System.config({
    packages: {        
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    }
  });
  System.import('app/boot')
        .then(null, console.error.bind(console));
</script>

这个答案可以提供有关模块分辨率如何工作的提示:

您可以使用Gulp及其插件进行此打包:

请参阅以下答案:

答案 1 :(得分:6)

我遇到了同样的问题,基本上你只需要在生产模式下运行webpack构建。

要执行此操作,请安装webpack globaly webpack -p安装完成后,从您的应用程序根目录运行distance()。这使我的文件大小从5MB以上减少到大约700KB

答案 2 :(得分:5)

虽然迟到了,现在来到这里的人......如果你正在使用angular2 +那么试试

ng build --prod --env=<staging or prod or your env file>

它将执行AoT,在一个命令中捆绑缓存清除和缩小。 更多deatils可以在Angular官方网站ng build section中找到。在我的情况下,chunk中的一个实际上是2.4MB,减少到450 + KB但是在包括--prod后它进一步减少到200 + KB

应用程序的大小取决于。 Angular2具有延迟加载代码或分块的概念。您可以将应用程序拆分为块(例如管理UI和用户UI)并按需加载它们,以便最初不需要加载整个应用程序,这将有助于减少加载时间。以下文章可能会有额外的帮助:

答案 3 :(得分:4)

您的问题很可能与发送给客户的文件大小有关。 6.9MB在网络和解析/评估时间方面都是巨大的。

建议:

  1. 缩小您的申请
  2. 将其拆分为多个捆绑包(vendors.js,core.js,...)

答案 4 :(得分:1)

另一种加快应用速度的方法是使用Lazy Loading

这样,您的appModule将减少导入,并且模块将按需调用。

答案 5 :(得分:1)

主要问题是polyfills上的zone.js,Zone.js大大降低了应用的运行速度