如何在MVC项目中发布帖子并获得作品 [英] How to make a post and get works in a MVC project

查看:52
本文介绍了如何在MVC项目中发布帖子并获得作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序,但我在打字稿和C#之间的连接方面苦苦挣扎. 我可以看到C#在Inspect中给出了响应,值在那里,但是我不知道如何在Typescript中处理.

I have an ASP.NET MVC app and I'm struggling with the connection between the typescript and the C#. I can see that the C# is giving the response in the Inspect, the value is there but I don't know how to treat in Typescript.

C#代码:

namespace TEST.Controllers
{
    [Route("api/[controller]")]
    public class TestController : Controller
    {

    // GET api/GetTest
    [HttpGet("GetTest")]
    public IEnumerable<string> GetTest()
    {
      return new string[] { "Teste1", "Teste2" };
    }
    }
}

TypeScript服务代码:

TypeScript SERVICE Code:

public getTest(): Observable<any> {

        return this.dataService.get(this.baseUrl + '/GetTest')
          .map((response: Response) => <any>response.json())
          // .do(data => console.log("All: " + JSON.stringify(data)))
          .catch(this.handleError);
}

数据服务代码(TypeScript):

Data Service Code (TypeScript):

public get<T>(url: string, params?: any): Observable<T> {
    const options = new DataServiceOptions();
    options.method = RequestMethod.Get;
    options.url = url;
    options.params = params;
    return this.request(options);
}
private request(options: DataServiceOptions): Observable<any> {
    options.method = (options.method || RequestMethod.Get);
    options.url = (options.url || '');
    options.headers = (options.headers || {});
    options.params = (options.params || {});
    options.data = (options.data || {});

    this.interpolateUrl(options);
    this.addXsrfToken(options);
    this.addContentType(options);
    this.addAuthToken(options);

    // this.addCors(options);

    const requestOptions = new RequestOptions();
    requestOptions.method = options.method;
    requestOptions.url = options.url;
    requestOptions.headers = options.headers;
    requestOptions.search = this.buildUrlSearchParams(options.params);
    requestOptions.body = JSON.stringify(options.data);

    this.pendingCommandsSubject.next(++this.pendingCommandCount);

    const stream = this.http.request(options.url, requestOptions)
        .catch((error: any) => {
            this.handleErrors(error);
            return Observable.throw(error);
        })
        .map(this.unwrapHttpValue)
        .catch((error: any) => {
            return Observable.throw(this.unwrapHttpError(error));
        })
        .finally(() => {
            this.pendingCommandsSubject.next(--this.pendingCommandCount);
        });

    return stream;
}

呼叫:

  private getDataBase() {

    this.service.getTest().subscribe((res) => {
       console.log(res);
      this._proceduresImportData = res;
     });


  }

OBS:我也可以安慰可观察对象,但是我不能治疗它.

OBS: I also can console the observable, but I cannot treat it.

推荐答案

解决此问题的最佳方法是拥有通用请求服务并封装您的服务调用,然后将其注入您需要的位置.以get为例(可以扩展)

The best way to approach this is to have a generic request service and encapsulate your service calls, then inject that in where you need it. Taking get for an example (this can be expanded upon)

request.service.ts

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

import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";

import { WindowRef } from "./window.service";

@Injectable()
export class RequestService {

    private baseUrl: string;

    constructor(private http: Http, private windowRef: WindowRef) {
        this.baseUrl = this.getBaseUrl();
    }

    public get<T>(resource: string): Observable<T> {
        return this.http.get(this.baseUrl + resource)
            .map<Response, T>(this.extractData);
    }

    private extractData(response: Response) {
        return response.json();
    }

    private getBaseUrl(): string {
        if (this.windowRef.getNativeWindow().location.hostname === "localhost") {
            return "http://localhostAddress/api/";
        } else if (this.windowRef.getNativeWindow().location.hostname === "anotherEnviroment") {
            return "https://anotherAddress/api/";
        }
    }
}

window.service.ts

import { Injectable } from "@angular/core";

@Injectable()
export class WindowRef {
    public getNativeWindow(): any {
        return window;
    }
}

然后,该方法返回您所期望的对象的可观察对象,该对象与解析器或onInit一起使用,可以在需要的地方订阅该对象.

This then returns an observable of the object you are expecting, used with a resolver or onInit it can be subscribed to where needed.

get-stuff.service.ts

    import { Injectable } from "@angular/core";
    import { Observable } from "rxjs/Observable";

    import { RequestService } from "../common/request.service";

    @Injectable()
    export class Service {

        constructor(private requestService: RequestService) { }

        public getTestService(): void {

            let requestedStuff: Observable<string[]> = this.requestService.get<string[]>(`GetTest`);

            requestedStuff.subscribe(stuff: string[]) => {
                 //do stuff with your string
            }
        }
    }

然后订阅并使用您的数据

Then subscribe and use your data

希望有帮助

这篇关于如何在MVC项目中发布帖子并获得作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆