I'm new to Angular and I'm creating a test Application to accelerate my understanding of the topic. Recently I encountered a challenge to integrate Angular2(FrontEnd) with Django(Backend) by fetching the data using REST APIs.
File: library.service.ts
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
// Project Modules
import { Library } from '../models';
#Injectable()
export class LibraryService {
private librariesUrl = 'http://127.0.0.1:8000/api/library/create-library/';
constructor(private http: Http) { }
private headers = new Headers({'Content-Type': 'application/json'});
private extractData(res: Response) {
return res.json();
}
private handleError (error: any) {
return Observable.throw(error.message || 'Server error');
}
getAll(): Observable<Library[]> {
return this.http.get(this.librariesUrl, {headers: this.headers})
.map((res) => this.extractData(res.json())).catch((err) => this.handleError(err));
}
}
File: libraries.component.ts
import { Component, OnInit} from '#angular/core';
import {HttpClient} from '#angular/common/http';
// Project Modules
import { Library } from '../models';
import { LibraryService } from './library.service';
#Component({
selector: 'app-libraries',
templateUrl: './libraries.component.html',
styleUrls: ['./libraries.component.css'],
})
export class LibrariesComponent implements OnInit {
libraries: Library[];
personalLibraries: Library[];
collaborativeLibraries: Library[];
constructor(private libraryService: LibraryService, private http: HttpClient) { }
ngOnInit(): void {
/*this.http.get('http://127.0.0.1:8000/api/library/create-library/').subscribe((data: Library[]) => {
console.log(data);
this.personalLibraries = data;
});*/
this.libraryService.getAll().subscribe(response => this.personalLibraries = response);
}
}
REST API
# Django Modules
from django.shortcuts import get_object_or_404
# REST Modules
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view, authentication_classes, permission_classes
# Project Modules
from .models import Resource, ResourceUserAssociation, Collection, Library
from mysite.utils import get_value_or_404, get_value_or_default, get_boolean
from .serializers import LibrarySerializer, CollectionSerializer
# TODO: Check user authentication here
class CreatorLibraryAPI(APIView):
def get(self, request, format=None):
# slug = get_value_or_404(request.GET, 'slug')
lib_object = Library.objects.filter(type='personal')
sdata = LibrarySerializer(lib_object, many=True).data
return Response(sdata, status=status.HTTP_200_OK)
JSON I'm Expecting
[
{
"slug": "tech-stack",
"title": "Technology Stack",
"description": "Library of resources related to Technology",
"type": "personal"
},
{
"slug": "biz-stack",
"title": "Technology Stack",
"description": "Library of resources related to Business",
"type": "personal"
},
{
"slug": "design-stack",
"title": "Design Stack",
"description": "Library of resources related to Design",
"type": "personal"
}
]
Important
When I try to fetch data in the Component only, then I successfully get the result [See the commented code in libraries.components.ts]. But somehow it's not working in the Service, am I doing something wrong with Observables?
Note
This problem is very similar to Question here.
Big thanks to the community in advance :)
Few changes I've made:
Used HttpClient instead of Http. This allows me to remove .map() as HttpClien already returns the JSON (instead of the whole response).
Correct File: library.service.ts
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '#angular/core';
import { Headers } from '#angular/http';
import {HttpClient} from '#angular/common/http';
// Project Modules
import { Library } from '../models';
#Injectable()
export class LibraryService {
private librariesUrl = 'http://127.0.0.1:8000/api/library/create-library/';
constructor(private http: HttpClient) { }
private headers = new Headers({'Content-Type': 'application/json'});
private handleError (error: any) {
console.log('---------- CATCH ERROR ----------');
return Observable.throw(error.message || 'this is some random server error');
}
getAll(): Observable<Library[]> {
return this.http.get(this.librariesUrl).catch((err) => this.handleError(err));
}
}
Related
I have created a Django and Angular application to upload files. It was working without errors until I integrated a login page. I have not been able to upload files since integration. I get 401 - "Unauthorized" error. What could have possibly gone wrong?
Auth-interceptor:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,HttpErrorResponse } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { catchError, Observable, throwError } from "rxjs";
import { LoginService } from "src/services/login.service";
#Injectable()
export class AuthInterceptorService implements HttpInterceptor {
constructor(private authService: LoginService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authService.isLoggedIn()) {
const token = this.authService.getAuthToken();
console.log("intercept",token)
// If we have a token, we set it to the header
request = request.clone({
setHeaders: {Authorization: `Token ${token}`}
});
}
return next.handle(request)
}
}
fileupload.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup } from '#angular/forms';
import { LoginService } from 'src/services/login.service';
import { FileUploader, FileLikeObject } from 'ng2-file-upload';
import { concat, Observable } from 'rxjs';
import { HttpEvent, HttpEventType } from '#angular/common/http';
#Component({
selector: 'app-fileupload',
templateUrl: './fileupload.component.html',
styleUrls: ['./fileupload.component.scss']
})
export class FileuploadComponent {
DJANGO_SERVER = 'http://127.0.0.1:8081'
public uploader: FileUploader = new FileUploader({});
public hasBaseDropZoneOver: boolean = false;
constructor(private formBuilder: FormBuilder, private uploadService: LoginService) { }
fileOverBase(event): void {
this.hasBaseDropZoneOver = event;
}
getFiles(): FileLikeObject[] {
return this.uploader.queue.map((fileItem) => {
return fileItem.file;
});
}
upload() {
let files = this.getFiles();
console.log(files);
let requests= [];
files.forEach((file) => {
let formData = new FormData();
formData.append('file' , file.rawFile, file.name);
requests.push(this.uploadService.upload(formData));
console.log(requests,file)
});
concat(...requests).subscribe(
(res) => {
console.log(res);
},
}
);
}}
console.log(err);
}
);
}}
service:
public upload(formData) {
let token= localStorage.getItem('token');
return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, formData).pipe(map((res) => {
console.log(res)
})
)
}
Thank you
I resolved the issue. It was because I was usign interceptor and I was using third party API for authentication. So instead of Django token, the third party APIs token was sent in header of POST request.
How I resolved it?
I used Httpbackend to process POST requests to Django DB so that the request is not intercepted and then I added custom header (with Django token to the reuest). I used the code snippet on this website: https://levelup.gitconnected.com/the-correct-way-to-make-api-requests-in-an-angular-application-22a079fe8413
Currently I am struggling with an error after try to use a few mat components like "mat-form-field" or "mat-date-range-input" etc..
I've already imported them in the app.module file as I always do with these kind of component, but I get many errors like this:
If 'mat-form-field' is an Angular component, then verify that it is part of this module
If 'mat-label' is an Angular component, then verify that it is part of this module.
I have to say that in the same project I am using mat-tab-group and mat-tab etc... and I have not any errors with them.
These is my code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AngularMaterialModule } from './angular-material.module/angular-material.module.module';
import { MatButtonToggleModule } from '#angular/material/button-toggle';
import { MatSlideToggleModule } from '#angular/material/slide-toggle';
import { MatCardModule } from '#angular/material/card';
import { MatFormFieldModule } from '#angular/material/form-field';
import { MatInputModule } from '#angular/material/';
import { MatIconModule } from '#angular/material/icon';
import { ClipboardModule } from '#angular/cdk/clipboard';
#NgModule({
declarations: [], // I've omitted this part because is not relevant to this issue
imports: [
BrowserModule,
AppRoutingModule,
AngularMaterialModule,
MatProgressSpinnerModule,
MatButtonToggleModule,
MatSlideToggleModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatIconModule,
ClipboardModule
],
providers: [{provide: LocationStrategy, useClass: PathLocationStrategy}],
bootstrap: [AppComponent]
})
export class AppModule { }
And my component : create.report.component.html
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [formGroup]="reportForm" [rangePicker]="picker">
<input matStartDate formControlName="from" placeholder="Start date">
<input matEndDate formControlName="to" placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
create.report.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, FormGroup, FormArray, FormControl } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-report',
templateUrl: './create.report.component.html'
})
export class CreateReportComponent implements OnInit {
reportForm = new FormGroup({
from: new FormControl(),
to: new FormControl()
});
constructor(
private router: Router,
private fb: FormBuilder) {
this.buildForm();
}
ngOnInit(): void {
}
buildForm() {
// console.log('***buildForm this.hmService***', this.hmService);
this.reportForm = this.fb.group( {
from : [ '', [Validators.required, Validators.minLength(5)]],
to: [ '', [Validators.required, Validators.minLength(5)]],
published : [ '', [Validators.required, Validators.minLength(5)]]
});
}
}
Ok, finally I solved!
With this line I fix the issue I had with material components. Now I can use them in my create.report.component .
import { CreateReportComponent } from './pages/report/create/create.report.component';
Can anyone help me with a simple question(I guess). I'm trying to display a json file in a table through Django into an Angular front end app. I can view the data by console logging it, however I can't seem to get the data into the webpage.
I know how to display the table in HTML. The specific problem is that the object which is fetched from the API does not appear in the HTML.
component.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, OnInit, ViewChild,
ViewEncapsulation } from '#angular/core';
import ApexChart from 'apexcharts'
import { ApexOptions } from 'ng-apexcharts';
import { FinanceService } from 'app/modules/admin/dashboards/finance/finance.service';
#Component({
selector: 'app-finance',
templateUrl: './finance.component.html',
styleUrls: ['./finance.component.scss'],
encapsulation : ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class FinanceComponent implements OnInit {
_stockData: any;
_portData: any;
_effData: any;
_calData: any;
_labels: any;
_table: any;
constructor(
private _financeService: FinanceService,
){
}
ngOnInit(): void {
this._financeService.getFinanceData()
.subscribe((res: any) => {
console.log(res);
this._stockData = res.stocks;
this._portData = res.port;
this._effData = res.eff;
this._calData = res.cal;
this._labels = res.labels;
this._table = res.table;
console.log(res.table);
this._prepareChartData();
},
(response) => {
// Re-enable the form
});
}
Service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { catchError, switchMap } from 'rxjs/operators';
import { BehaviorSubject, of, Observable } from 'rxjs';
import { environment } from 'environments/environment';
#Injectable({
providedIn: 'root'
})
export class FinanceService {
/**
* Constructor
* #param {HttpClient} _httpClient
*/
constructor(private _httpClient: HttpClient){
}
// -----------------------------------------------------------------------------------------------------
// # Public methods
// -----------------------------------------------------------------------------------------------------
/**
* get Finance Data
*/
getFinanceData(): Observable<any>{
return this._httpClient.get(environment.baseURL + 'apiurls/', {}).pipe(
switchMap((response: any) => {
return of(response);
})
);
}
}
template.html
<div>
<p>{{_table.Percentage}}</p>
</div>
json (as presented by the django API)
{
"stocks":[],
"eff":[],
"port":[],
"cal":[],
"labels":[],
"table":{
"Percentage":{
"AD.AS":16.1,
"ASML.AS":15.67,
"AAPL":68.23
},
"Budget":{
"AD.AS":241.5,
"ASML.AS":235.05,
"AAPL":1023.45
},
"Closing":{
"AD.AS":25.22,
"ASML.AS":314.3,
"AAPL":129.04
},
"Number of stocks to buy":{
"AD.AS":10.0,
"ASML.AS":1.0,
"AAPL":8.0
},
"final":{
"AD.AS":252.0,
"ASML.AS":314.0,
"AAPL":1032.0
},
"final allocation":{
"AD.AS":15.77,
"ASML.AS":19.65,
"AAPL":64.58
},
"Diff":{
"AD.AS":-0.33,
"ASML.AS":3.98,
"AAPL":-3.65
}
}
}
To display the json data on html you may use json pipe
<pre>
{{ _table.Percentage | json }}
</pre>
i am trying to develop django/angular project and using base user model for django user.
I tried to implement JWT auth in both side. On django side i am using rest_framework_jwt library.
I checked the token flow from client-side to server-side. With a simple login page on angular i use my username and password for logging in. It's accepting my data and redirects me to the main page where i use a service to get "feed" data from server-side. In this step it gives me 403 error. By the way when i use Postman for checking the scenerios im adding jwt as a authorization header like "JWT " and it still give me "Authentication credentials were not provided". Waiting your helps. Thanks.
django -> settings.py middleware ;
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
django -> settings py rest_framework ;
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATON_CLASSES':(
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
'NON_FIELD_ERRORS_KEY': 'global',
}
i use these settings for jwt
#JWT SETTINGS
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': timedelta(days=2) # datetime imported at start
}
using classic urls.py ( its and included part so it begins with api/auth/ )
urlpatterns = [
path('login/', obtain_jwt_token),
path('refresh-token/', refresh_jwt_token),
]
in front end i have a interceptor, authservice and feedservice
authservice
import { Injectable } from '#angular/core';
import { HttpClient, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '#angular/common/http';
import { tap, shareReplay } from 'rxjs/operators';
import * as JwtDecode from 'jwt-decode';
import * as moment from 'moment';
import { JWTPayload } from '../interfaces/JWTPayload';
// logs in and out, notifies other components with subscription
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
URL_API = 'http://localhost:80/api/auth';
constructor(private http: HttpClient) { }
private setSession(authResult) {
const token = authResult.token;
const payload = <JWTPayload>JwtDecode(token);
const expiresAt = moment.unix(payload.exp);
localStorage.setItem('token', authResult.token);
localStorage.setItem('expires_at', JSON.stringify(expiresAt.valueOf()));
}
get token(): string {
return localStorage.getItem('token');
}
login(username: string, password: string) {
return this.http.post(`${this.URL_API}/login/`, { username, password })
.pipe(tap(
response => {
console.log("API CALL RESPONSE FOR LOGIN => ", response);
this.setSession(response);
}
),
shareReplay(),
);
}
logout() {
localStorage.removeItem('token');
localStorage.removeItem('expires_at');
console.log("CIKIS YAPILDI ");
}
refreshToken() {
if (moment().isBetween(this.getExpiration().subtract(1, 'days'), this.getExpiration())) {
return this.http.post(
`${this.URL_API}/refresh-token/`,
{ token: this.token }
).pipe(
tap(response => { this.setSession(response); console.log("response for refresh token=>", response); }),
shareReplay(),
).subscribe();
}
}
getExpiration() {
const expiration = localStorage.getItem('expires_at');
const expiresAt = JSON.parse(expiration);
console.log("expires=>", moment(expiresAt).calendar());
return moment(expiresAt);
}
isLoggedIn() {
return moment().isBefore(this.getExpiration());
}
isLoggedOut() {
return !this.isLoggedIn();
}
}
interceptor
import { Injectable } from '#angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '#angular/router';
import { AuthenticationService } from '../services/authentication.service';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '#angular/common/http';
import { Observable } from 'rxjs';
// intercepts every api call and adds jwt header to call.
#Injectable({
providedIn: 'root'
})
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('token');
console.log("firs token check => ", token);
if (token) {
console.log("gecerli token=> ", token)
const cloned = req.clone({
headers: req.headers.set('Authorization', 'JWT '.concat(token))
});
console.log("cloned ->", cloned.body);
return next.handle(cloned);
} else {
console.log("next.handle(req) => ", next.handle(req));
return next.handle(req);
}
}
}
feedservice
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from "rxjs";
import { Post } from '../interfaces/Post';
#Injectable({
providedIn: 'root'
})
export class FeedService {
API_URL = 'http://localhost:80'
constructor(private httpClient: HttpClient) { }
public getFeed(): Observable<Post[]> {
return this.httpClient.get<Post[]>(`${this.API_URL}/api/feed/`);
}
public retrievePost(post_id: number): Observable<Post> {
return this.httpClient.get<Post>(`${this.API_URL}/api/feed/${post_id}`)
}
public postFeed(post: Post) {
return this.httpClient.post(`${this.API_URL}/api/feed/`, post)
}
}
and in finale there is login component
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { Router, ActivatedRoute } from '#angular/router';
import { first } from 'rxjs/operators';
import { AuthenticationService } from '../services/authentication.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup
returnUrl: string
loading = false;
submitted = false;
error = '';
constructor(
private formBuilder: FormBuilder,
private authenticationService: AuthenticationService,
private router: Router,
private route: ActivatedRoute
) {
//redirect home if already logged in
if (authenticationService.isLoggedIn()) {
console.log("isLoggedIn() => already logged in")
router.navigate(['/']);
}
}
ngOnInit(): void {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
//get returl url or redirect to /
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
//easy way to access fields
get f() { return this.loginForm.controls }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) { console.log("if code block => invalid credentials"); return; }
this.loading = true;
this.authenticationService.login(this.f.username.value, this.f.password.value)
.subscribe(
success => { console.log("succesfull login"); this.router.navigate([this.returnUrl]); },
error => {
this.error = error;
this.loading = false;
console.log("errors =>", error);
}
);
}
}
I figured it out. In my other api's view i added those lines
permission_classes = [ IsAuthenticated ]
authentication_classes = [ JSONWebTokenAuthentication ]
and it worked!
I have been folllowing the ionic tutorial:
10 Minutes with Ionic 2: Calling an API
Typescript Error
Module '"C:/Users/grace/imaginemai/client/apiApp/src/providers/people->service/people-service"' has no exported member 'PeopleSevice'.
C:/Users/grace/imaginemai/client/apiApp/src/pages/home/home.ts
import { NavController } from 'ionic-angular';
import {PeopleSevice} from >'C:\Users\grace\imaginemai\client\apiApp\src\providers\people-> >service\people-service';
I am not sure what I am doing wrong. I noticed that there were possible errors with the original tutorial so I made some amendments as per a correction posted in the comments: https://github.com/ah3243/ionic2ApiExample/blob/master/src/providers/people-search.ts
I am still having issues - I've followed the tutorial but used my own API from a blog I am developing with Django. So although the ionic app is called peopleservice, I am expecting it to produce blog posts. The code is pasted below. Please could someone tell me what I am doing wrong.
Thanks in advance.
people-service.ts:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the PeopleServiceProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class PeopleService {
data1: any;
constructor(public http: Http) {
console.log('Hello PeopleService Provider');
}
load() {
if (this.data1) {
return Promise.resolve(this.data1);
}
//dont have the data yet
return new Promise(resolve => {
this.http.get('localhost:8000/posts/')
.map(res => res.json())
.subscribe(data => {
this.data1 = data.results;
resolve(this.data1);
});
});
}
}
home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {PeopleSevice} from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [PeopleSevice]
})
export class HomePage {
public posts: any;
constructor(public navCtrl: NavController, public peopleService: PeopleService) {
this.loadPosts();
}
loadPosts() {
this.PeopleService.load()
.then(data1 => {
this.posts = data1;
})
}
}
app.module.ts:
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
/*import { PeopleService } from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';*/
#NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
/*StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
PeopleService*/
]
})
export class AppModule {}
app.component.ts:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { TabsPage } from '../pages/tabs/tabs';
import { PeopleService } from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = TabsPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}
home.html:
<ion-header>
<ion-navbar *navbar>
<ion-title>
Home
</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="home">
<ion-list>
<ion-item *ngFor="let post of posts">
<h2>{{post.title}}</h2>
<p>{{post.text}}</p>
</ion-item>
</ion-list>
</ion-content>
folder structure:
blog
>client
>apiApp
>src
>app
>app.component.ts
>app.html
>app.module.ts
>app.scss
>main.ts
>pages
>providers
>people-service
>people-service.ts
You have to use relative paths for importing.
import {PeopleSevice} from 'C:\\Users\\grace\\imaginemai\\client\\apiApp\\src\\providers\\people-service\\people-service';
This kind of absolute path will not work.
Try:
import {PeopleSevice} from '../../providers/people-service/people-service';
This is the relative path from the current file.