CopyPastor

Detecting plagiarism made easy.

Score: 0.7703390121459961; Reported for: String similarity Open both answers

Possible Plagiarism

Plagiarized on 2019-07-06
by ORBIT

Original Post

Original - Posted on 2013-07-03
by Brian Swift



            
Present in both answers; Present only in the new answer; Present only in the old answer;

**Async Pipe & Observables**
The first approach that we'll take a look doesn't require any modification at the API level. In light of this, we'll be using the Async Pipe. Pipes in Angular work just as pipes work in Linux. They accept an input and produce an output. What the output is going to be is determined by the pipe's functionality. This pipe accepts a promise or an observable as an input, and it can update the template whenever the promise is resolved or when the observable emits some new value. As with all pipes, we need to apply the pipe in the template.
Let's assume that we have a list of products returned by an API and that we have the following service available:
// api.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ApiService { constructor(private http: HttpClient) { } getProducts() { return this.http.get('http://localhost:3000/api/products'); } }
The code above is straightforward - we specify the `getProducts()` method that returns the `HTTP GET` call.
It's time to consume this service in the component. And what we'll do here is create an Observable and assign the result of the `getProducts()` method to it. Furthermore, we'll make that call every 1 second, so if there's an update at the
**API level, we can refresh the template:**
// some.component.ts
import { Component, OnInit, OnDestroy, Input } from '@angular/core'; import { ApiService } from './../api.service'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/switchMap'; @Component({ selector: 'app-products', templateUrl: './products.component.html', styleUrls: ['./products.component.css'] }) export class ProductsComponent implements OnInit { @Input() products$: Observable<any>; constructor(private api: ApiService) { } ngOnInit() { this.products$ = Observable .interval(1000) .startWith(0).switchMap(() => this.api.getProducts()); } }
And last but not least, we need to apply the async pipe in our template:
<!-- some.component.html --> <ul> <li *ngFor="let product of products$ | async">{{ product.prod_name }} for {{ product.price | currency:'£'}}</li> </ul>
This way, if we push a new item to the API (or remove one or multiple item(s)) the updates are going to be visible in the component in 1 second.
> Note In your case

@Input() products$: Observable<any>; ngOnInit() { this.products$ = Observable .interval(1000) .startWith(0).switchMap(() => getTournament(id)); } getTournament(id: string): Observable<YourObject>{ const url = `${this.getUrl}/${id}`; //console.log(url); return this.http.get<YourObject>(url, httpJSON); }
> Html <!-- some.component.html --> <ng-container *ngFor="let item of products$ | async | paginate: { itemsPerPage: 5, currentPage: p }; let i = index"> <tr> <td>{{item.name }}</td> <!-- <td>{{item.awayTeam}}</td> <td>{{item.homeTeam}} </td> --> <td>{{item.line }}</td> <td>{{item.oddsAmerican}}</td> </tr> </ng-container> </ul>

The ASP.Net Web API has replaced the WCF Web API previously mentioned.
I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service c#".
Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.
Here's how your example would look when implemented using the ASP.Net Web API Client Library:
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; namespace ConsoleProgram { public class DataObject { public string Name { get; set; } } public class Class1 { private const string URL = "https://sub.domain.com/objects.json"; private string urlParameters = "?api_key=123"; static void Main(string[] args) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // List data response. HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. if (response.IsSuccessStatusCode) { // Parse the response body. var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll foreach (var d in dataObjects) { Console.WriteLine("{0}", d.Name); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } //Make any other calls using HttpClient here. //Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous. client.Dispose(); } } }
If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed
For more details, including other examples, go here: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
This blog post may also be useful: http://johnnycode.com/2012/02/23/consuming-your-own-asp-net-web-api-rest-service/

        
Present in both answers; Present only in the new answer; Present only in the old answer;