AngularJS版本6. *服务方法未定义

时间:2018-06-18 22:22:37

标签: javascript angular angular-services

所以我只是尝试编写一个组件和服务,从一个视图获取用户输入并将其传递给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);
    };
  }
}

我不明白为什么会收到此错误:

Error

所以我将服务记录下来以查看对象,奇怪的是该方法被放置在原型中:

Prototype

我不明白,我做错了吗?

1 个答案:

答案 0 :(得分:2)

您如何称呼handleSubmit方法?

错误表明它无法读取login的{​​{1}}属性,这意味着undefinedthis.userServiceundefined方法在原型中的事实是可以的。请记住login

我认为您以某种棘手的方式致电gets are deep and sets are shallow,这使handleSubmit引用其他对象而不是您认为的那样。

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

将此添加到组件构造函数

this

有关详细信息,请参阅此帖子:Angular pass callback function to child component as @Input