Angular zu Web API 13: Api URL in Angular Frontend eintragen
Angular
Frontend
IN VISUAL CODE
1) In der
Environments.ts
Man trägt die Verbindung in der environment Datei
ein.
Environments.ts
export const environment = {
production:false,
apiUrl: "https://localhost:7073/api/Articles"
};
|
2) API: Controller
URL in Service eintragen
Dann trägt man in die service.ts Datei ein
Services/articles.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Article } from '../models/article';
import { environment } from 'src/environments/environment'; //*for
url route to web api
@Injectable({
providedIn: 'root'
})
export class ArticlesService {
//----< ArticlesService
>----
//*opens webapi and gets data
private url = "Articles";
//*inject HttpClient to call api
constructor(private http: HttpClient) { } //*inject web-api caller
//*get array of articles in observable
public getArticles(): Observable<Article[]> {
var apiUrl = environment.apiUrl + "/" + this.url;
return this.http.get<Article[]>(apiUrl);
}
//----</
ArticlesService >----
}
|
Dann den Aufruf in der App.module.ts erweitern
import { HttpClientModule } from '@angular/common/http';
|
App.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
3) In Component URL
im Service aufrufen
Daten laden
in app.component on Init
App.component.ts
import { Component } from '@angular/core';
import { Article } from './models/article';
import { ArticlesService } from './services/articles.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
//--------< export: Component
>--------
//< variables >
title = 'CodeDocu_Frontend';
//*add dummy data
articles: Article[]=[]; //empty start
//</ variables >
//*init
constructor(private articlesService:ArticlesService){}
//< events >
//when components starts
ngOnInit():void{
//*get articles from api
this.articlesService.getArticles().subscribe((result: Article[])=>(this.articles = result));
}
//</
events >
//--------<
export: Component >--------
}
|