#angular #angular2-routing
#угловой #angular2-маршрутизация
Вопрос:
У меня есть вид ChatbotComponent
, который не привязан ни к какой конфигурации маршрута.
@Component({
selector: 'app-chatbot',
templateUrl: './chatbot.component.html',
styleUrls: ['./chatbot.component.css'],
providers: [UsersService, OrganizationService]
})
Директива вызывается в соответствии app.compononent.html покрывается модулем приложения:
<app-logo></app-logo>
<router-outlet></router-outlet>
<app-footer></app-footer>
<app-chatbot></app-chatbot>
Это мой routing.yaml
const routes: Routes = [
{ path: '', component: LoginComponent, pathMatch: 'full', canActivate: [AuthenticationGuard]},
{ path: 'accueil', component: AccueilComponent, canActivate: [AuthenticationGuard] },
{ path: '**', redirectTo: '' }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
Я спрашиваю, есть ли какой-либо способ защитить ChatbotComponent
через my AuthenticationGuard
, чтобы остановить вызовы api, выполняемые в компоненте!
Это небольшое представление о моих зависимостях:
-- @angular/animations@5.2.11
-- @angular/cli@1.7.4
| -- @angular-devkit/build-optimizer@0.3.2
| -- @angular-devkit/core@0.3.2
| -- @angular-devkit/schematics@0.3.2
| -- @schematics/angular@0.3.2
-- @angular/common@5.2.11
-- @angular/compiler@5.2.11
-- @angular/compiler-cli@5.2.11
-- @angular/core@5.2.11
-- @angular/forms@5.2.11
-- @angular/http@5.2.11
-- @angular/language-service@5.2.11
-- @angular/platform-browser@5.2.11
-- @angular/platform-browser-dynamic@5.2.11
-- @angular/router@5.2.11
-- angular-in-memory-web-api@0.5.4
Спасибо
Ответ №1:
Вы можете просто использовать *ngIf
<app-chatbot *ngIf="isAuthenticated"></app-chatbot>
Где вы должны определить isAuthenticated
в своем app.component.ts и назначить, true
если пользователь аутентифицирован, и false
в противном случае.
Редактировать: например, в вашем app.component.ts
export class AppComponent implements OnInit {
public isAuthenticated: boolean = false;
constructor(
private authenticationService: AuthenticationService
) {
}
// Authentication service has an obsevable authenticated that emits a value when the user authentication status changes.
// in ngOnInit subscribe to that value
public ngOnInit(): void {
this.authenticationService.authenticated$.subscribe((val) => {
this.isAuthenticated = val;
});
}
}
Комментарии:
1. Эй, @Sherid мне нужно определить IsAuthenticated в AppComponent!! И как связать это с моей защитой!
2. Эй, @Sherid это небольшая деталь, на самом деле AuthenticationService будет вызываться дважды