Angular 5 - 为不同的模块使用相同的路径

时间:2018-03-09 12:10:44

标签: angular angular5 serverside-rendering angular-universal

如果你们碰巧是facebook用户,你可能会注意到网址" https://www.facebook.com "用户登录或注销时不会更改。我在构建的应用程序中遇到了同样的问题(使用角度5)。虽然有一些建议的解决方案:

  1. 首先使用相同的路由,一个组件(比如:home),在home的模板中我们插入带有* ngIf的in,out(组件),在运行时我们检查用户是否已记录in或out并基于我们显示相应的(in或out)组件。
  2.   

    home.component.html

    <app-in *ngIf="loggedIn"></app-in>
    <app-out *ngIf="!loggedIn"></app-out>
    
    1. 我认为第二种方法更干净,特别是在使用延迟加载时,是连续两条路径具有相同的空路径,并使用<保护(例如:第一个)强大>匹配,现在老实说这仍然很难看,因为匹配器不是用于这种高级用法(它也是同步的,并没有包含在服务中 - 例如 canLoad ,< strong> canActivate ..等等 - 人们可以轻松注入其他服务(例如: authService )以检查是否登录或退出。
    2.   

      home.routing.ts

      .
      .
      .
      
      const routes: Routes = [
        {
          matcher: matcherFunc,
          loadChildren: './in/in.module#InModule'
        },
        {
          path: '',
          loadChildren: './out/out.module#OutModule'
        }
      ];
      
      .
      .
      .
      

      这是匹配函数:

      export function matcherFunc(url: UrlSegment[]) {
        let currentUser;
      
      
          currentUser = localStorage.getItem('user');
      
        if (url.length === 0 && currentUser) {
          return ({ consumed: url });
        } else {
          return null;
        }
      }
      

      当我将我的应用升级为通用时问题变得更糟,因为在那种情况下我必须在服务器端处理全局变量(window,localStorage..etc) 我被困在哪里!

      我相信这个问题已经有一段时间没有令人满意的答案,有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以通过使用Angular的useFactory提供程序提供RouterModule的ROUTES来使用处理应加载哪个模块的模块。

代码可能是这样的。


use PHPMailer\PHPMailer\PHPMailer;
use Aws\Ses\SesClient;
use Aws\Ses\Exception\SesException;
require 'vendor/autoload.php';

if(!function_exists("sendmailalexraw")){

function sendmailalexraw($email,$subject,$messages,$definesender)
{



// Replace sender@example.com with your "From" address. 
// This address must be verified with Amazon SES.
$sender = $definesender;           
$sendername = 'Alex';

// Replace recipient@example.com with a "To" address. If your account 
// is still in the sandbox, this address must be verified.
$recipient = $email;    

// Specify a configuration set.
$configset = 'ConfigSet';

// Replace us-west-2 with the AWS Region you're using for Amazon SES.
$region = 'eu-west-1'; 

$subject = $subject;

$htmlbody = <<<EOD
<html>
<head></head>
<body>
<h1>Hello!</h1>
<p>Please see the attached file for a list of customers to contact.</p>
</body>
</html>
EOD;

$textbody = <<<EOD
Hello,
Please see the attached file for a list of customers to contact.
EOD;

//// The full path to the file that will be attached to the email. 
$att = 'path/to/customers-to-contact.xlsx';

// Create an SesClient.
$client = SesClient::factory(array(
    'version'=> 'latest',     
    'region' => $region
));

// Create a new PHPMailer object.
$mail = new PHPMailer;

// Add components to the email.
$mail->setFrom($sender, $sendername);
$mail->addAddress($recipient);
$mail->Subject = $subject;
$mail->Body = $htmlbody;
$mail->AltBody = $textbody;
$mail->addAttachment($att);
$mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configset);

// Attempt to assemble the above components into a MIME message.
if (!$mail->preSend()) {
    echo $mail->ErrorInfo;
} else {
    // Create a new variable that contains the MIME message.
    $message = $mail->getSentMIMEMessage();
}

// Try to send the message.
try {
    $result = $client->sendRawEmail([
        'RawMessage' => [
            'Data' => $messages
        ]
    ]);
    // If the message was sent, show the message ID.
    $messageId = $result->get('MessageId');
    echo("Email sent! Message ID: $messageId"."\n");
} catch (SesException $error) {
    // If the message was not sent, show a message explaining what went wrong.
    echo("The email was not sent. Error message: "
         .$error->getAwsErrorMessage()."\n");
}

}
}



$email='example@gmail.com';
$subject='abc';
$messages='xyz';
$definesender='info@verifieddomain.net';
sendmailalexraw($email,$subject,$messages,$definesender);


?>


然后在您的AppRoutingModule中,路径“”的模块将成为HandlerModule:

// HandlerModule

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule
  ],
  providers: [
    {
      provide: ROUTES,
      useFactory: configHandlerRoutes,
      deps: [SessionService],
      multi: true
    }
  ]
})


export class HandlerModule {}

export function configHandlerRoutes(sessionService: SessionService) {
  let routes: Routes = [];
  if (sessionService.isLoggedIn()) {
    routes = [
      {
        path: '', loadChildren: './in/in.module#InModule'
      }
    ];
  } else {
    routes = [
      {
        path: '', loadChildren: './out/out.module#OutModule'
      }
    ];
  }
  return routes;
}

在SessionService之后,您必须在提供方法isLoggedIn的值更改时更新Router.config,因为该应用程序将仅加载首次加载的页面(模块)。这是因为HandlerModule中useFactory提供程序使用的函数“ configHandlerRoutes”仅在我们第一次导航到“”路径时才执行,之后Angular Router已经知道他必须加载哪个模块。

最后,您必须在SessionService中完成

// AppRoutingModule

 {
    path: '',
    loadChildren: './handler/handler.module#HandlerModule'
 }

就是这样。

如果您想再参考一下,这里是一篇文章,他们使用相同的方法:https://medium.com/@german.quinteros/angular-use-the-same-route-path-for-different-modules-or-components-11db75cac455