如何发布帖子并在MVC项目中获得作品

时间:2017-10-16 08:47:19

标签: c# asp.net-mvc angular typescript

我有一个ASP.NET MVC应用程序,我正在努力解决打字稿和C#之间的联系。 我可以看到C#在Inspect中给出了响应,价值在那里,但我不知道如何在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 SERVICE代码:

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):

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:我也可以安装observable,但我无法对待它。

1 个答案:

答案 0 :(得分:2)

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

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一起使用,它可以在需要的地方订阅。

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
            }
        }
    }

然后订阅并使用您的数据

希望有所帮助