我正在尝试制作post
,但我无法将数据发送到provider
。
在我收到信息的页面上,我可以正确显示它们,但当我尝试将它们发送给提供者时,它们会显示为undefined
或结果为空。
它还会显示错误:选项http://my.url/api/todo 401(未经授权)和未捕获(在承诺中):状态为响应:URL为0:空
modal.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ReviewService } from '../../providers/review-service';
@Component({
selector: 'page-modal',
templateUrl: 'modal.html'
})
export class ModalPage {
private url: string = "http://my.url";
pessoa = [];
constructor(private _service: ReviewService) { }
peopleForm() {
console.log(this.pessoa); // Aqui eu consigo pegar as informações
this._service.novo(this.pessoa).then(res => {
console.log("Enviou para o provider");
})
}
}
查看-service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class ReviewService {
private url = 'http://my.url/post';
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
private headers = new Headers({'Content-Type': 'application/json'});
constructor(public http: Http) { }
novo(pessoa: Array<string>) {
console.log("Exibir o que recebeu: " + pessoa); // Aqui me retorna undefined ou vazio
return this.http
.post(this.url, JSON.stringify(pessoa), {headers: this.headers})
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
}
答案 0 :(得分:0)
您可以像这样对服务 进行身份验证。
import { CanActivate, Router } from '@angular/router';
import { Injectable } from '@angular/core';
/**
* Class that deals with redirect to login if user tries to
* access any route without being logged in.
**/
@Injectable()
export class CanActivateAuthGuard implements CanActivate {
constructor(private router: Router) { }
/**
* Overrides abstract methods that grants the permison to access a url
* if token is stored in Angular Local Storage.
**/
canActivate(): boolean {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser) {
return true;
} else {
this.router.navigate(['/login/login']);
return false;
}
}
}
在每个 routing.module 中使用它:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CanActivateAuthGuard } from '../shared/auth/auth.service';
const routes: Routes = [
{
path: '',
canActivate: [CanActivateAuthGuard],
data: {
title: 'General User'
},
children: [
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class GeneralRoutingModule {}