angular - Angular2将身份验证令牌传递给另一个服务
问题描述
我有以下代码,我在其中获取 Auth 令牌,
@Injectable()
export class AuthenticationService {
@Input() isValid:boolean=false;
constructor(private http: HttpClient, private router: Router) { }
auth_token:string;
/** sign in user */
login(username, password) {
this.req = this.http.post('URL for Authenticaion', {
"username": username,
"password": password
})
.subscribe(
result => {
console.log(result);
this.router.navigate(['dashboard']);
}
}
现在我想将此令牌传递给另一个将检索所有数据的服务。我面临的问题是 result.auth_token 是当前块的本地,因此在它之外无法识别。我如何返回它的值?
解决方案
You can use Subject/BehaviorSubject which will act as observer and observable. You can emit the token and catch in the another service. Here is the code
In AuthenticationService:
private modelAlertEvent = new Subject<any>();
public modelAlertEventObservable = this.modelAlertEvent.asObservable();
this.modelAlertEvent.next(token);
In Another Service
this.modelsubscribe = this.authservice.modelAlertEventObservable.subscribe(token=>{
console.log(token);
});
推荐阅读
- webrtc - 无法连接到 Coturn 服务器
- hibernate - 在 MappedSuperClass 中自动装配存储库
- python - 构建包含不同测量值的 PyMC3 模型
- reactjs - React Hooks 状态总是落后一步
- azure - 将自定义 docker 容器部署到应用服务时,.NET 核心应用程序前面的反向代理?
- php - 如何在 Ubuntu 18.10 上使用 Laravel Homestead 设置 HTTPS
- python - 如何在每个循环中遍历不同数量的元素?
- c# - TimeZoneInfo.ConvertTimeFromUtc 没有将旧日期转换为夏令时
- asp.net-core - Swashbuckle.AspNetCore 所需的查询字符串参数
- c++ - 从 VS2015 升级到 VS2017 后编译错误