将一项服务注入另一项服务并可以访问角度为7的注入服务成员

时间:2019-06-21 20:03:49

标签: angular typescript angular-services angular-components

我在这里阅读的所有内容:https://angular.io/guide/dependency-injection-in-action使这看起来应该可行,但是当尝试从另一个服务调用注入的服务中的方法时出现此错误:

  

TypeError:无法读取未定义的属性'isLoggedIn'       在CatchSubscriber.handleError [作为选择器](project.service.ts:30)       在CatchSubscriber.error(catchError.js:29)       在TapSubscriber._error(tap.js:56)       在TapSubscriber.error(Subscriber.js:55)       在MapSubscriber._error(Subscriber.js:75)       在MapSubscriber.error(Subscriber.js:55)       在FilterSubscriber._error(Subscriber.js:75)       在FilterSubscriber.error(Subscriber.js:55)       在MergeMapSubscriber.notifyError(OuterSubscriber.js:7)       在InnerSubscriber._error(InnerSubscriber.js:14)

这是我的ProjectService,正在注入我的UserService

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError, of } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { AuthHeader } from '../../Shared/Helpers/AuthHeader';
import { UserService } from '../../User/Services/user.service';

@Injectable({
  providedIn: 'root'
})
export class ProjectService {

  constructor(private http: HttpClient, private userService: UserService) {

  }
  private projectsApiEndPointRoot = '/api/ProjectApi/';
  test(): Observable<number> {
    return <Observable<number>>this.http.get<number>(this.projectsApiEndPointRoot + "getimages/8", { headers: AuthHeader.getAuthHeader() }).pipe(
      tap(data => console.log(data)),
      catchError(this.handleError)
    );
  }

  private handleError(err: HttpErrorResponse) {
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      if (err.status == 401 || err.status == 403) {
        console.log(this.userService.isLoggedIn());
      }
      else {
        errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
      }
    }
    console.error(errorMessage);
    return throwError(errorMessage);
  }
}

UserService只是有一个方法,无论用户是否登录,该方法都应返回布尔值。我在多个组件上成功使用了相同的方法,但是当尝试从其他服务调用它时它不起作用

这不可能吗?

编辑:添加UserService的位进行演示:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError, of, BehaviorSubject } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { EmailModel } from '../Models/EmailModel';
import { ILoginRequest } from '../Interfaces/ILoginRequest';
import { ILoginResponse } from '../Interfaces/ILoginResponse';
import { IRegistrationRequest } from '../Interfaces/IRegistrationRequest';
import { Router } from '@angular/router';


@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient, private router: Router) { }
  private usersApiEndPointRoot = 'api/UserApi/';

  private loggedIn = false;
  ...

  isLoggedIn() {
    return this.loggedIn;
  }


  private handleError(err: HttpErrorResponse) {
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
    }
    console.error(errorMessage);
    return throwError(errorMessage);
  }
}

3 个答案:

答案 0 :(得分:4)

问题在于您正在用户服务上传递函数。调用它时,this的值将成为窗口。

请使用lambda函数,而不是将函数传递给catchError函数,以便保留该函数。对test()方法进行以下更改,您的问题将得到解决:

test(): Observable<number> {
  return <Observable<number>>this.http.get<number>(this.projectsApiEndPointRoot + 
      "getimages/8", { headers: AuthHeader.getAuthHeader() }).pipe(
    tap(data => console.log(data)),
    catchError(err => this.handleError(err)) // <--
  );
}

答案 1 :(得分:2)

您需要在catchError中使用箭头函数才能使用此类上下文。

catchError((err) => this.handleError(err))

否则上下文会丢失。

答案 2 :(得分:0)

我也将我的评论作为答案,因为它与其他答案有些不同。

像这样更改方法的签名

private handleError = (err: HttpErrorResponse) => {...}

然后,您可以根据需要保留catchError(this.handleError)