错误TS2304:找不到名称“ httpOptions”

时间:2019-03-19 01:54:48

标签: angular typescript django-rest-framework

在当前将Angular集成到我的Django应用程序的教程中,我在实现服务以从Django REST Framework API中提取数据方面遇到了麻烦。

我不断收到错误消息,说“找不到名称'httpOptions'”,我不知道如何解决它。

teacher.service.ts

import {UserService} from './user.service';

@Injectable()
export class TeacherService {

  constructor(private http: HttpClient, private _userService: UserService) { }

  // Uses http.get() to load data from a single API endpoint
  list() {
    return this.http.get('/api/teachers');
  }

  // send a POST request to the API to create a new data object
  create(post, token) {
    httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'JWT ' + this._userService.token   // this is our token from the UserService (see Part 1)
      })
    };
    return this.http.post('/api/teachers', JSON.stringify(post), httpOptions);
  }
}

相关的user.service.ts

@Injectable()
export class UserService {

  private httpOptions: any;
  public token: string;
  public token_expires: Date;
  public username: string;
  public errors: any = [];

  constructor(private http: HttpClient) {
    this.httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json'})
    };
  }
}

2 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题。

create(post, token) {
let appHeaders = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'JWT ' + this._userService.token   
  });

return this.http.post('/api/teachers', JSON.stringify(post), { headers: appHeaders });
}

或者类似以下的简单方法可以解决该问题。

let httpOptions = { ... } 

快乐编码

答案 1 :(得分:0)

问题是您正在访问全局变量而不使用它。所以尝试一下,

return this.http.post('/api/teachers', JSON.stringify(post), this.httpOptions);

或者您必须像这样定义createPost方法(定义局部变量)

create(post, token) {
    let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'JWT ' + this._userService.token   // this is our token from the UserService (see Part 1)
      })
    };
    return this.http.post('/api/teachers', JSON.stringify(post), httpOptions);
  }