我正在尝试创建一个Rest API,但我遇到了一些问题。 事实上,post函数不是在C#API上触发的,我不知道为什么用于getAll()函数的GET函数运行良好。
Angular Service:
public GetAll = (): Observable<Expertise[]> => {
return this.http.get(this.actionUrl, '').map((response: Response) => <Expertise[]>response.json());
}
public Add = (thingToAdd: Expertise): Observable<Expertise> => {
thingToAdd.Id = 1;
let toAdd = JSON.stringify(thingToAdd);
console.log(toAdd);
console.log(this.actionUrl);
return this.http.post(this.actionUrl, toAdd, { headers: this.headers
}).map((response: Response) => response.json());
}
C#API:
// GET api/values
[HttpGet]
public async Task<IEnumerable<Expertise>> Get()
{
try
{
System.Console.WriteLine("Test get all");
//var result = await cvService.Get("toto@azeo.com");
return new List<Expertise>();
}
catch (System.Exception ex)
{
logger.LogError(ex.Message, ex);
throw;
}
}
// POST api/values
[HttpPost]
public Expertise Post([FromBody]Expertise expertise)
{
try
{
System.Console.WriteLine("Test post");
context.Expertises.Add(expertise);
context.SaveChanges();
logger.LogInformation("New expertise added !");
return expertise;
}
catch (System.Exception ex)
{
logger.LogError(ex.Message, ex);
throw;
}
}
专业知识(EF模型):
public class Expertise
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ExpCV> CVs { get; set; }
}
如果有人有想法&#34;链接&#34;服务和我的API告诉我,我已经坚持了很长时间。
提前谢谢
答案 0 :(得分:0)
由于您的服务返回TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
,因此在您订阅该观察结果之前,不会发生实际observable
和GET
次请求。
看看我设置的这个plunker:
plunker:https://plnkr.co/edit/r6aBaB3BjJzdIS4myAd8?p=preview
代码:
POST
searhService:
@Component({
selector: 'app',
template: `
<button (click)="searchNoSub()">searchNoSub</button>
<button (click)="search()">search</button>
`
})
export class App {
constructor(private searchService:SearchService) {
}
search(){
this.searchService.search().subscribe(console.log,console.log)
}
searchNoSub(){ this.searchService.search(); }
}
现在在Chrome中打开您的devtools和@Injectable()
export class SearchService {
constructor(private http: Http) {}
search(term: string) {
// get artists named john from spotify API
return this.http.get('https://api.spotify.com/v1/search?q=john&type=artist')
.map((response) => response.json());
}
}
标签,查看新请求:
点击network
时,您会注意到网络标签中未注册任何请求。
点击searchNoSub
按钮后,您会看到我们订阅的请求。
简而言之,您需要订阅可观察的请求。