AngularJS 版本 6.* 即将推出未定义的服务方法

AngularJS Version 6.* Service method is coming up undefined

所以我只是想编写一个组件和服务,从一个视图获取用户输入并将其传递给 api 进行验证。问题是在我的组件中,它说该服务基本上没有方法 login 并且未定义。但是,我已经非常仔细地检查并重新检查了 Angular.io 的文档,但无法正常工作。

LoginComponent.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from '../../../services/user.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  constructor(private userService: UserService) {
    console.log('userService', userService);
  }

  ngOnInit() {}

  handleSubmit(data) {
    // https://api-test.sarahlawrence.edu:82/
    this.userService.login(data)
      .subscribe(user => console.log('user', user));
  }
}

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs/index';
import { catchError, map, tap } from 'rxjs/internal/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

interface CredsInterface {
  username: string;
  password: string;
};

interface LoggedIn {
  token: string;
}

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

  private apiUrl = '<apiUrl>';

  constructor(
    private http: HttpClient
  ) { }

  login (creds: CredsInterface): Observable<any> {
    console.log('UserService.login()', creds);

    return this.http.post<any>(`${this.apiUrl}/signin`, creds, {})
      .pipe(
        tap((loggedIn: LoggedIn) => {
          console.log(`Login: ${loggedIn}`);
        }),
        catchError(this.handleError('login()', []))
      );
  }

  /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}

我不明白为什么会出现此错误:

所以我注销了服务以查看对象,奇怪的是该方法被放置在原型中:

我不明白,我做错了什么吗?

如何调用 handleSubmit 方法?

错误说它无法读取 undefinedlogin 属性 这意味着 this.userServiceundefinedlogin 方法在原型内部这一事实是可以的。请记住 gets are deep and sets are shallow

我认为您调用 handleSubmit 时使用了一些棘手的方法,这使得 this 引用了您认为的其他对象。


我刚看过 stackblitz。您使用 [onHandleSubmit]="handleSubmit" 传递对您的函数的引用,但是当它被执行时 this 不再是您的 LoginComponent。

将其添加到组件构造函数中

this.handleSubmit = this.handleSubmit.bind(this)

有关详细信息,请参阅此 post: