服务无法达到发布功能
服务无法达到发布功能
嘿(第一次在这里发布,所以我可能会违反一些规则,如果我违反了,请告诉我),\n我正在尝试创建一个Rest API,但遇到一些问题。\n事实上,C# API上的post函数没有被触发,而GET函数与getAll()函数一起使用时运行良好。\nAngular服务:\n
public GetAll = (): Observable=> { return this.http.get(this.actionUrl, '').map((response: Response) => response.json()); } public Add = (thingToAdd: Expertise): Observable => { 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()); }
\nC# API:\n
// GET api/values [HttpGet] public async Task> Get() { try { System.Console.WriteLine("Test get all"); //var result = await cvService.Get("toto@azeo.com"); return new List (); } 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; } }
\nExpertise(EF模型):\n
public class Expertise { [Key] public int Id { get; set; } public string Name { get; set; } public ICollectionCVs { get; set; } }
\n如果有人有办法“链接”我的服务和API,请告诉我,我已经卡在这上面很长时间了。\n非常感谢。
问题的原因是因为在service中返回的observable,直到订阅这个observable之后,实际的GET和POST请求才会发生。
解决方法是在订阅请求observable之前,先在service中添加订阅操作。
以下是一个示例的代码:
import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; export class SearchService { constructor(private http: Http) {} search() { // 向Spotify API发送GET请求,搜索名字为john的艺术家 return this.http.get('https://api.spotify.com/v1/search?q=john&type=artist') .map((response) => response.json()); } }
在组件中使用这个service:
import { SearchService } from './search.service'; export class App { constructor(private searchService: SearchService) {} search() { this.searchService.search().subscribe(console.log, console.log); } searchNoSub() { this.searchService.search(); } }
你可以在浏览器的开发者工具中的"network"选项卡下观察到以下情况:
当点击"searchNoSub"按钮时,你会注意到在网络选项卡中没有任何请求被注册。
当点击"search"按钮时,你会看到一个请求,这是因为我们订阅了请求observable。
简而言之,你需要在请求observable之前先进行订阅操作。