gpt4 book ai didi

c# - Angular http获取使用c#.Net

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:49 24 4
gpt4 key购买 nike

我是 Angular 2.4 的新手,使用的是 Visual Studio 2017。我使用 .NET Core 1.1 创建了一个项目。我正在尝试使用 Angular Tour of Heroes 教程中的一些代码。我使用 Web API 在 Visual Studio .Net 中创建了一个 Controller ,它成功返回了一个包含客户数据的 JSON 文件。

与教程类似,我正在创建一个 customer.service.ts 和 customers.component.ts。

我在调用 getCustomers() 时收到 404 文件未找到错误。我无法弄清楚为什么它不起作用。任何帮助将不胜感激。

这是 customer.service.ts 的代码片段:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Customer } from './customer';

@Injectable()
export class CustomerService {
private customerUrl = 'api/customer'; // URL to web api
private headers = new Headers({ 'Content-Type': 'application/json' });
private customers: Customer[];

constructor(private http: Http) { }

getCustomers(): Promise<Customer[]> {
return this.http.get('api/customer')
.toPromise()
.then(response => response.json() as Customer[])
.catch(this.handleError);
}

private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}

这是 customers.component.ts 的代码片段:

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Customer } from './customer';
import { CustomerService } from './customer.service';

@Component({
selector: 'customers',
templateUrl: './customers.component.html',

// an array of style file names (with paths).
styleUrls: ['./customers.component.css'],
})

export class CustomersComponent implements OnInit {
title = 'Northwind Customers';
public customers: Customer[];
selectedCustomer: Customer;
http: Http;

constructor(private router: Router, private customerService: CustomerService) { }

onSelect(customer: Customer): void {
this.selectedCustomer = customer;
}

getCustomers(): void {
//this.customers = this.customerService.getCustomers();
this.customerService.getCustomers().then(customers => this.customers = customers);
}

ngOnInit(): void {
this.getCustomers();
}
}

这是 customers.component.html:

<h1>{{title}}</h1>

<h2>Customers</h2>

<div>
<label>Company name:</label> <input #companyName />
<button (click)="add(companyName.value); companyName.value=''">Add</button>
</div>

<ul>
<li *ngFor="let customer of customers"
[class.selected]="customer === selectedCustomer">
<span class="badge">{{customer.customerID}}</span>
<span>{{customer.companyName}}</span>

</li>
</ul>

这是 customer.ts:

export class Customer {
customerID: string;
companyName: string;
contactName: string;
contactTitle: string;
address: string;
city: string;
region: string;
postalCode: string;
country: string;
phone: string;
fax: string;
}

我的 ASP.NET Controller 似乎可以正常工作。当我在浏览器中导航到 api/customer 时,它会返回一个包含数据的 JSON 文件。这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NorthwindAngular.DAL;
using NorthwindAngular.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace NorthwindAngular.Controllers
{
[Route("api/[controller]")]
public class CustomerController : Controller
{
private readonly NorthwindContext _context;

public CustomerController(NorthwindContext context)
{
_context = context;
}

// GET: api/values
//[HttpGet("[action]")]
[HttpGet]
public IEnumerable<Customer> Get()
{
return _context.Customers.ToList();
}

// GET: api/values
[HttpGet("{id}")]
public Customer Get(string id)
{
if (String.IsNullOrEmpty(id))
return null;
else
return _context.Customers.Find(id);
}

// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

最佳答案

我终于让它工作了。解决方案是使用 Observable 而不是 Promise 重做 http.get 调用。

参见 Fetch data with http.get()在 Angular 文档中了解更多详细信息。

客户服务.ts

这里的关键是 ASP.NET 返回没有数据元素的 JSON,所以 extractData 函数需要使用 body 而不是 body.data 显示在 Tour of Heroes Tutorial 中.

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map'

import { Customer } from './customer';

@Injectable()
export class CustomerService {
private customerUrl = 'api/customers'; // URL to web api
private headers = new Headers({ 'Content-Type': 'application/json' });
private customers: Customer[];

// the Angular Http client service is injected into the constructor
constructor(private http: Http) { }

getCustomers(): Observable<Customer[]> {
return this.http.get(this.customerUrl)
.map(this.extractData)
.catch(this.handleError);
}

private extractData(res: Response) {
let body = res.json();
return body || {};
}

private handleError(error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;

if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}

console.error(errMsg);

return Observable.throw(errMsg);
}
}

客户.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';

import { Customer } from './customer';
import { CustomerService } from './customer.service';

@Component({
selector: 'customers',
templateUrl: './customers.component.html',

// an array of style file names (with paths).
styleUrls: ['./customers.component.css'],
})

export class CustomersComponent implements OnInit {
title = 'Northwind Customers';
customers: Customer[];
selectedCustomer: Customer;
errorMessage: string;
http: Http;

// Inject a Router nad CustomerService needed by this component
constructor(private router: Router, private customerService: CustomerService) { }

onSelect(customer: Customer): void {
this.selectedCustomer = customer;
}

gotoDetail(): void {
// Note that you're passing a two-element link parameters array
// — a path and the route parameter
//this.router.navigate(['/customer-detail', this.selectedCustomer.customerID]);
}

getCustomers(): void {
//this.customers = this.customerService.getCustomers();
this.customerService.getCustomers()
.subscribe(
customers => this.customers = customers,
error => this.errorMessage = <any>error);
}

ngOnInit(): void {
this.getCustomers();
}
}

customer.component.html

<h1>{{title}}</h1>

<h2>Customers</h2>

<div>
<label>Company name:</label> <input #companyName />
<button (click)="add(companyName.value); companyName.value=''">Add</button>
</div>

<ul>
<li *ngFor="let customer of customers"
[class.selected]="customer === selectedCustomer"
(click)="onSelect(customer)">
<span class="badge">{{customer.customerID}}</span>
<span>{{customer.companyName}}</span>
<button class="delete"
(click)="delete(customer); $event.stopPropagation()">x</button>

</li>
</ul>

<div *ngIf="selectedCustomer">
<h2>
<!--
Pipes are a good way to format strings, currency amounts,
dates and other display data.
-->
{{selectedCustomer.companyName | uppercase}} is my hero
</h2>
<button (click)="gotoDetail()">View Details</button>
</div>

<div class="error" *ngIf="errorMessage">
{{ errorMessage }}
</div>

关于c# - Angular http获取使用c#.Net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43176401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com