[英]Error TS2304: Cannot find name 'httpOptions'
在当前将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'})
};
}
}
我认为这可以解决您的问题。
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 = { ... }
快乐的编码
问题是您正在访问全局变量而不使用它。 试试这个,
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.