首页 > 解决方案 > 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 是当前块的本地,因此在它之外无法识别。我如何返回它的值?

标签: angular

解决方案


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);
});

推荐阅读