您好,我决定创建一个登录页面,但我无法发送发布请求。我正在使用@angular rc.6 版本
登录.ts
@Component({
selector: 'login',
templateUrl: 'app/views/login.html',
providers: [ LoginService ],
styleUrls: [ 'css/login.css' ]
})
export class Login {
postData: string;
constructor(private _loginService: LoginService) {}
onLogin(user : string, password: string) {
if (!user && !password){return;}
this._loginService.login(user , password)
.subscribe (
data => this.postData = JSON.stringify({user : user , password: password}),
error => alert(error),
() => console.log(this.postData)
);
}
}
登录.html
<label for="user">User</label>
<input type="text" id="user" #user>
<label for="password">Password</label>
<input type="password" id="password" #password>
<button type="submit" (click)="onLogin(user.value, password.value); user.value=''; password.value=''">Login</button>
登录服务.ts
@Injectable()
export class LoginService {
constructor (private _http: Http){}
private loginUrl = './users';
login(user: string, password: string): Observable<User> {
let body = JSON.stringify({"user": user, "password": password});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this._http.post(this.loginUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
告诉我为什么它不起作用?
有必要制作一个 REST Web 服务,这个视频帮助我弄清楚了如何去做https://www.youtube.com/watch?v=0RIrdFfy9t4