【问题标题】:how can return value to component using subscribe in service file?如何使用服务文件中的订阅向组件返回值?
【发布时间】:2019-09-12 19:07:37
【问题描述】:

我使用 http 请求作为单独的服务。我也使用 authguard 作为服务。从 authguard 服务订阅后,我想将数据返回到登录组件。但我无法将数据返回到组件。

http服务函数

createp(entity: any, ep:string): Observable<string> {
    return this.http.post(ep, entity, {responseType: 'text'})
    .pipe(
      tap((reticapp: string) => this.log(`added entity w/ id=${reticapp}`)),
      catchError(this.handleError<string>('create'))
    );
  }    

认证服务功能

login(auth: Auth) {
    sessionStorage.setItem('token', 'token');

    const loginData: any = {
      email: auth.email,
      password: auth.password
    };
    const url = environment.apiEndpoint + '/pau/v1/ses';

    this.authService.createp(loginData, url).subscribe(result => {
      this.result = result;
    });
}

从组件调用'onlogin()函数

onLogin(form: NgForm) {
    if (form.invalid) {
      return;
    }
    this.loginUser = {
      email: form.value.email,
      password: form.value.password
    };
    this.authService.login(this.loginUser);
  }

我已尝试在调用 authservice 后添加订阅。但是当它添加页面刷新时。

我想获取组件的返回数据如何获取呢?

【问题讨论】:

  • 数据结果在this.result,你试过返回吗?
  • @FilipeManuel 我试过了。但是当它在组件上使用时。它是未定义的。

标签: angular


【解决方案1】:

您应该像这样将订阅移动到组件 ts 文件中 服务:

login(auth: Auth) {
    sessionStorage.setItem('token', 'token');

    const loginData: any = {
      email: auth.email,
      password: auth.password
    };
    const url = environment.apiEndpoint + '/pau/v1/ses';

    this.authService.createp(loginData, url);
}

组件

  onLogin(form: NgForm) {
        if (form.invalid) {
          return;
        }
        this.loginUser = {
          email: form.value.email,
          password: form.value.password
        };
        this.authService.login(this.loginUser).subscribe(result => {
          this.loginResult = result;
        });
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多