简体   繁体   English

在每个页面上运行的Angular6应用程序逻辑

[英]Angular6 app logic that runs on every page

I'm converting from AngularJS to Angular6 currently but am not finding any solutions to this question. 我目前正在从AngularJS转换为Angular6,但我找不到任何解决方案。

Where is it best practice to keep app logic that needs to run on every page that the angular app loads on? 最好的做法是保持需要在角度应用程序加载的每个页面上运行的应用程序逻辑?

Example logic is logging a user in based on a cookie stored on the machine. 示例逻辑基于存储在机器上的cookie来记录用户。 Where should I put this logic to check for the cookie and log the user in? 我应该在哪里使用此逻辑来检查cookie并将用户登录?

The best place I've seen thus far is in app.component.ts . 到目前为止我见过的最好的地方是app.component.ts I used to accomplish this in AngularJS via loading a GlobalController on all pages and then loading a HomepageController etc that would load for the specific "partial" that was plugged into the page. 我曾经在AngularJS中通过在所有页面上加载GlobalController然后加载一个将加载到插入页面的特定“部分”的HomepageController等来完成此操作。

e/ To clarify, this was just an example and isn't the ONLY business logic I need to run on every page. e /澄清一下,这只是一个例子,并不是我需要在每个页面上运行的唯一业务逻辑。 I need to trigger backend requests every ~10 seconds that check timers on the server (for app timeouts/etc). 我需要每隔约10秒触发后端请求,检查服务器上的计时器(对于app超时/等)。

you should put that logic in the app.components.ts 你应该把这个逻辑放在app.components.ts中

import { Component } from "@angular/core";

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})
export class AppComponent {
    // here goes your logic
}

For authenticating Http requests you can you HttpInterceptors to append a token to each request for your API. 为了验证Http请求,您可以通过HttpInterceptors将令牌附加到API的每个请求。 Something like this -> 像这样的东西 - >

my-http.interceptor.ts 我-http.interceptor.ts

 @Injectable()
 export class MyHttpInterceptor implements HttpInterceptor {

   constructor() {}

      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
         const token = 'my_token'; // retrieve token from your storage.
         const req = request.clone({
             setHeaders: {
               Authorization: `Bearer ${token}`
             }
           });

           return next.handle(req).do((event: HttpEvent<any>) => {
             // success
             if (event instanceof HttpResponse) {
             }
           }, (err: any) => {
             // failure
             if (err instanceof HttpErrorResponse) {
             }
           });
       }
 }

Then register your http interceptor on either your CoreModule or AppModule. 然后在您的CoreModule或AppModule上注册您的http拦截器。

 providers: [
     { provide: HTTP_INTERCEPTORS, useClass: MyHttpInterceptor, multi: true}
 ]

RouteGuards can be used to block certain routes for any reason you want - User isn't authorized, User doesn't have the proper role to access, ect... RouteGuard可用于阻止您想要的任何原因的某些路由 - 用户未经授权,用户没有正确的角色可以访问,等等...

https://codecraft.tv/courses/angular/routing/router-guards/ https://codecraft.tv/courses/angular/routing/router-guards/


If you want to execute logic on Route change you can listen in on the router.events. 如果你想在Route change上执行逻辑,你可以监听router.events。

How to detect a route change in Angular? 如何检测Angular中的路由变化?


Edit: As other people in this thread pointed out, always put business logic in a service. 编辑:正如此线程中的其他人所指出的,始终将业务逻辑放在服务中。

For a best practice angular app structure -> https://itnext.io/choosing-a-highly-scalable-folder-structure-in-angular-d987de65ec7 有关角度应用程序结构的最佳实践 - > https://itnext.io/choosing-a-highly-scalable-folder-structure-in-angular-d987de65ec7

you can create an authentication service (auth.service.ts) in your app and make it singleton, that service will contain all auth operation like (login, logout, getProfile...) after that you can inject that service and use it everywhere in your app when needed. 您可以在您的应用程序中创建一个身份验证服务(auth.service.ts)并使其成为单例,该服务将包含所有身份验证操作,如(login,logout,getProfile ...)之后您可以注入该服务并在任何地方使用它在需要时在您的应用中。

i recommend that you separate your app into modules and create a module for authentication. 我建议您将应用程序分成模块并创建用于身份验证的模块。

and for everything shared you can create a shared module that contains shared components, services, pipes, interceptors ... 对于共享的一切,您可以创建一个包含共享组件,服务,管道,拦截器的共享模块......

I would use Angular service and i would call it from app.component 我会使用Angular 服务 ,我会从app.component调用它

It Says 它说

Services are a great way to share information among classes that don't know each other. 服务是在彼此不了解的类之间共享信息的好方法。

Here's an example of solving your particular problem by using an AuthenticationService and a CanActivate route guard. 以下是使用AuthenticationService和CanActivate路由保护解决您的特定问题的示例。 The below Guard can be bound to whatever route (page) you please, be it one or all of them. 以下Guard可以绑定到您喜欢的任何路径(页面),无论是其中一个还是全部。

 @Injectable() class AuthenticationService { constructor () { } isLoggedIn() { // check your cookie logic here } } @Injectable() class AuthenticationGuard implements CanActivate { constructor(private authenticationService: AuthenticationService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { return this.authenticationService.isLoggedIn() .pipe( tap(loggedIn => { if (!loggedIn) { this.router.navigate(['/login'], { queryParams: { nextUrl: state.url } }); } }) ); } } @NgModule({ ... imports: [ RouterModule.forRoot([ { path: 'dummyRoute/', loadChildren: './components/dummyModule/dummy.module#DummyModule', canActivate: [ AuthenticationGuard ] }, ]) ], ... }) export class AppModule {} 

While using AppComponent to run code on every page is a solution, I would only recommend it as a last resort. 虽然使用AppComponent在每个页面上运行代码是一种解决方案,但我只推荐它作为最后的手段。 For the most part, Guards (used for authorising navigation steps), Resolvers (used for retrieving data required by the page prior load) and Interceptors (used to alter / filter HttpClient requests) used in conjunction with Services provide you with a more elegant way to solve these problems and keep your codebase neatly organised. 在大多数情况下,Guards(用于授权导航步骤),Resolvers(用于检索页面加载前所需的数据)和拦截器(用于更改/过滤HttpClient请求)与Services一起使用,为您提供更优雅的方式解决这些问题,并保持您的代码库整洁有序。

More on guards here https://angular.io/guide/router#guards . 更多关于守卫的信息,请访问https://angular.io/guide/router#guards

A full example of an authentication guard implementation: https://angular.io/guide/router#canactivate-requiring-authentication 身份验证防护实现的完整示例: https//angular.io/guide/router#canactivate-requiring-authentication

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM