Tips for creating and obtaining content in a model-view-controller (MVC) project

I am facing a challenge with the connection between my ASP.NET MVC app's TypeScript and C# code. While I can see that the C# code is giving the response in the Inspect, the value is there but I am unsure how to handle it in TypeScript.

C# Code:

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

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

The Calling:

  private getDataBase() {

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


  }

Note: I am able to log the observable, however, I am unable to properly handle it.

Answer №1

One effective approach is to create a generic request service that encapsulates your service calls and inject it where necessary. Let's take the example of a 'get' method (this concept can be further elaborated upon).

request-handler.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-handler.service";

@Injectable()
export class RequestHandlerService {

    private baseUrl: string;

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

    public fetch<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://localhost/api/";
        } else if (this.windowRef.getNativeWindow().location.hostname === "anotherEnv") {
            return "https://anotherDomain/api/";
        }
    }
}

window-handler.service.ts

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

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

This will result in an observable of the expected object which can be subscribed to as needed, such as with a resolver or during initialization.

data-fetcher.service.ts

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

import { RequestHandlerService } from "../shared/request-handler.service";

@Injectable()
export class DataFetcherService {

    constructor(private requestHandlerService: RequestHandlerService) { }

    public fetchData(): void {

        let fetchedData: Observable<string[]> = this.requestHandlerService.fetch<string[]>(`GetData`);

        fetchedData.subscribe(data: string[]) => {
             //perform actions with the retrieved data
        }
    }
}

You can then subscribe and utilize the data accordingly.

I hope this explanation proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to add unique elements to an array in Angular without any duplicates

I need help with pushing elements into an array and decrementing the count of it without duplicates in angular. Any assistance would be greatly appreciated ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

The element labeled as [control_name] is unrecognized and does not correspond to any known element within the system. This issue may arise from a compilation error within the website or due to the absence of

It might seem like a repetitive question, but after extensive research, I am still unable to find a solution. Before I resort to re-installing VS 2013, I am turning to you all for help. Just to provide some context, I am working with Visual Studio 2013 an ...

Utilizing JSON for sending model data to a controller in ASP.NET Core

I'm a beginner with ASP.NET Core and I'm attempting to send a view model to my controller. Data Model: public class ToolModel { public ToolModel() { } public string text { get; set; } public string type { get; set; } public stri ...

Adjustable angular-design sidebar with collapsible sections

My goal is to create a mat-drawer that can be resized and will collapse its content when it reaches a certain min-width. I've implemented this library to make the mat-drawer resizeable, which seems to be working well. The issue I'm encountering ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

The image referenced in the assets folder could not be located within the SCSS

Although I've come across similar questions, none of the solutions provided seem to work for me. I've tried them all, but they just don't seem to do the trick. My goal is quite simple - I just want to set a background image using CSS. Howev ...

Dealing with tag conflicts in Angular with ngx-translate

Within my student.component.ts file, I am constructing table output using the following code: var html = ...... html +='<li><a class="fanta" data-element-id="' + student.Id + '">Set as Draft</a></li& ...

Validation of identification numbers in South Africa

Despite doing thorough research, I am unable to make the code work. South African ID numbers contain information about the individual's date of birth and gender. My goal is to extract this information and validate it when a user enters their ID number ...

steps for making a specific cell editable in tabulatorI'm happy to help

click here for image description required initializeTabulatortableBng() { let thisClass = this; let bngTableData = thisClass.tableDataWorm; function formatDecimal(cell) { var value = cell.getValue(); if (value !== null && value !== undefine ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

Are you looking for straightforward dynamic directives that come with dynamic controllers and a scope?

Feeling like I have a simple problem to solve here. Working within the confines of a TypeScript + Angular application. Within a controller, I've got an array of similar directives that I want to utilize. These are essentially the panels strewn throug ...

How can I display only the search results in a DataGridview and hide the rest of the rows?

Is there a way to modify my code so that only the search results are displayed? Currently, when I perform a search, the search result is highlighted while the others remain unchanged. I've been attempting to hide the other rows and only display the ...

custom tooltip for ngx-charts

I am currently working on implementing a customized tooltip for heatmap cells using ngx-charts-heat-map. The challenge I'm facing is that the data I want to display does not fall under series, value, or name. It actually comes from a different propert ...

Replace the css variables provided by the Angular library with custom ones

Having an angular library with a defined set of css variables for colors applied to components, which are globally set like this: :root { -color-1: #000000; -color-2: #ffffff; ... } In my application utilizing this library, I need to override ...

Building a comprehensive setup project that offers users complete control within a C# winform application

Is there a way to develop an installer for a C# WinForms application that allows all users to easily run and modify the connection string in the app.config file? ...

Error Encountered when Trying to Utilize Vue Component Getter in TypeScript Mixin (Error Code: TS233

Here is the code snippet that I am currently working with: import {Component, Vue} from 'vue-property-decorator'; @Component({}) export default class MyMixin extends Vue { scrollToTop(): void { let scrollingWrapper: any = (this.$refs[th ...

I am looking for a way to transfer data collected from an input form directly to my email address without the need to open a new window. As of now, I am utilizing angular

Is there a way to send this data to my email address? I need help implementing a method to achieve this. {Name: "John", phoneNumber: "12364597"} Name: "John" phoneNumber: "12364597" __proto__: Object ...

Is it correct to implement an interface with a constructor in TypeScript using this method?

I am completely new to TypeScript (and JavaScript for the most part). I recently came across the article discussing the differences between the static and instance sides of classes in the TypeScript handbook. It suggested separating the constructor into an ...