I try to upload file in Angular. I added a button that calls the post a method that writes an image to a database and saves it to a folder "assets". This image must show up in . This file is successfully post and stored on assets but it doesn`t shows up and i get error
But after i reload Angular CLI server it already works.
My input
<div class="form-group">
<label for="inputPhotoGame">Select a game photo</label>
<input type="file" class="form-control-file" id="inputPhotoGame" (change)="fileProgress($event)">
</div>
My img
<img alt="photo" [src]=game.img_game>'''
Component class
'''import { Component, OnInit } from '#angular/core';
import {Genre} from '../../models/Genre';
import {MatIconRegistry} from '#angular/material';
import {CustomIconService} from '../../services/CustomIconService';
import {Game} from '../../models/Game';
import {FormComponent} from '../form/form.component';
import {GameService} from '../../services/GameService';
#Component({
selector: 'app-add-game',
templateUrl: './add-game.component.html',
styleUrls: ['./add-game.component.scss']
})
export class AddGameComponent implements OnInit {
genresList: Genre [];
searchStringForFiltrSearchArcade: string = '';
selectedPlatformIcon: string = '';
fileToUpload: File = null;
game: Game = new Game();
previewUrl:any = null;
constructor(private customIconService: CustomIconService, private gameService: GameService) {
this.customIconService.init();
this.genresList = [{name: 'Arcada'}, {name: 'Sport Simulator'}, {name: 'MOBA'}, {name: 'MMO RPG'}, {name: 'RPG'}, {name: 'Shuter'}];
}
ngOnInit() {
}
changePlatform() {
switch (this.game.platform_game) {
case 'Xbox': {
this.selectedPlatformIcon = 'icon-xbox';
break;
}
case 'PlayStation': {
this.selectedPlatformIcon = 'icon-ps';
break;
}
case 'PC': {
this.selectedPlatformIcon = 'icon-pc';
break;
}
default: alert("Error");
}
}
handleFileInput(fileInput: any){
// this.fileToUpload = files.item(0);
// console.log(this.fileToUpload);
// this.gameService.postFile(this.fileToUpload,"16");
// alert("file upload")
}
fileProgress(fileInput: any) {
this.fileToUpload = <File>fileInput.target.files[0];
this.preview();
}
preview() {
let mimeType = this.fileToUpload.type;
if (mimeType.match(/image\/*/) == null) {
return;
}
let reader = new FileReader();
reader.readAsDataURL(this.fileToUpload);
reader.onload = (_event) => {
this.previewUrl = reader.result;
};
this.gameService.postFile(this.fileToUpload,"16");
}
}
Service class
import {Injectable} from "#angular/core";
import {HttpClient} from "#angular/common/http";
import {Observable} from "rxjs";
import {Game} from "../models/Game";
#Injectable()
export class GameService {
private readonly usersUrl: string;
constructor(private httpClient: HttpClient) {
this.usersUrl = 'http://localhost:8080/api/v1/all';
}
public find(): Observable<Game[]> {
return this.httpClient.get<Game[]>(this.usersUrl);
}
postFile(fileToUpload: File, idGame: string) {
const endpoint = 'http://localhost:8080/api/v1/uploadFile/'+idGame;
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
this.httpClient
.post(endpoint, formData, { headers: {"cache-control": "no-cache"} }).subscribe((val) => {
console.log(val);
});
return false;
}
}
And html page
error
After reload Angular CLI server
Your app is loaded in memory when doing "ng serve". Adding files in your assets won't get them in memory.
You should get your files from you api (something like http://localhost:8080/api/v1/file/FileID)
Related
For more context, I'm trying set the form state with previously added data to the grid when I click on the Edit button in my application.
The problem is that the everything is set except for the uploaded file, yet I'm passing it down with a setEditFormState function from the 'facade.ts' to my 'component.ts'
setEditFormState(selectedRow: SrvUrgentCareAdviceSheets) {
this.store.dispatch(
new SetValueAction(ADD_EDIT_ADVICE_SHEET_FORM_ID, {
...addEditAdviceSheetInitialValue,
title: selectedRow.title,
category: box(selectedRow.category),
description: selectedRow.description,
isDeleted: selectedRow.deleted,
fileName: selectedRow.file,
id: selectedRow.id,
}),
);
console.log('SELECTEDROW', selectedRow);
}
And it is called in my component.ts like this:
ngOnInit(): void {
this.facade.getCategoryItems();
if (this.isEdit && this.openPayload) {
this.facade.setEditFormState(this.selectedRow);
}
console.log(this.selectedRow);
}
The file upload component is seperate and looks like this:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '#angular/common/http';
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '#angular/core';
import { FileInfo, SelectEvent } from '#progress/kendo-angular-upload';
import { SrvFileUploadResults } from '#servelec/data-types';
import { Observable, of } from 'rxjs';
#Component({
selector: 'srv-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FileUploadComponent implements HttpInterceptor {
#Input()
isMultiple = false;
#Output()
uploaded: EventEmitter<SrvFileUploadResults> = new EventEmitter<SrvFileUploadResults>();
uploadSaveUrl = 'mockUpload';
public myFiles: Array<FileInfo> = [];
onSelect(ev: SelectEvent) {
ev.files.forEach((file: FileInfo) => {
console.log(file.httpSubscription);
console.log(file.state);
if (file.rawFile) {
const reader = new FileReader();
this.myFiles.push(file);
reader.onloadend = () => {
const dataUrl = reader.result as string;
this.uploaded.emit({
filename: file.name,
content: dataUrl.substring(dataUrl.indexOf(',') + 1),
});
};
reader.readAsDataURL(file.rawFile);
}
});
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url === this.uploadSaveUrl) {
const success = of(new HttpResponse({ status: 200 }));
return success;
}
return next.handle(req);
}
}
Here you can see that all fields get set, except for the uploaded file.
Dear I am developing a page with Angular 7 and I am presented with the error TS2559: Type 'BookInterface[]' has no properties in common with type 'BookInterface', I have changed the code but I still can not find the solution, I leave the code below, the error is thrown in the method getListBooks(): this is my file list-books.component.ts
import { BookInterface } from './../../../models/book';
import { DataApiService } from './../../../services/data-api.service';
import { Component, OnInit } from '#angular/core';
import {NgForm} from '#angular/forms';
#Component({
selector: 'app-list-book',
templateUrl: './list-book.component.html',
styleUrls: ['./list-book.component.css']
})
export class ListBookComponent implements OnInit {
constructor(private dataApi: DataApiService) { }
private books: BookInterface = {};
ngOnInit() {
this.getListBooks();
}
getListBooks() {
this.dataApi.getAllBooks().subscribe(books => {
this.books = books;
});
}
onDelete() {
console.log('LIBRO ELIMINADO');
}
}
I also leave the code of my data-api.service.ts from where I call the interface
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs/internal/Observable';
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '#angular/fire/firestore';
import { BookInterface } from '../models/book';
#Injectable({
providedIn: 'root'
})
export class DataApiService {
constructor(private afs: AngularFirestore) {
this.bookCollecction = afs.collection<BookInterface>('books');
this.books = this.bookCollecction.valueChanges();
}
private bookCollecction: AngularFirestoreCollection<BookInterface>;
private books: Observable<BookInterface[]>;
private bookDoc: AngularFirestoreDocument<BookInterface>;
private book: Observable<BookInterface>;
getAllBooks() {
return this.books = this.bookCollecction.snapshotChanges()
.pipe(map( changes => {
return changes.map( action => {
const data = action.payload.doc.data() as BookInterface;
data.id = action.payload.doc.id;
return data;
});
}));
}
// metodo que trae un libro a traves de su id
getOneBook(idBook: string) {
this.bookDoc = this.afs.doc<BookInterface>(`books/${idBook}`);
return this.book = this.bookDoc.snapshotChanges().pipe(map(action => {
if (action.payload.exists === false){
return null;
} else {
const data = action.payload.data() as BookInterface;
data.id = action.payload.id;
return data;
}
}));
}
addBook(book: BookInterface): void {
this.bookCollecction.add(book);
}
updateBook(book: BookInterface): void {
let idBook = book.id;
this.bookDoc = this.afs.doc<BookInterface>(`books/${idBook}`);
this.bookDoc.update(book);
}
deleteBook(idBook: string): void {
this.bookDoc = this.afs.doc<BookInterface>(`books/${idBook}`);
this.bookDoc.delete();
}
}
The version of typescript that I am currently using is Version 2.7.2, but also update it without solving the problem
You need to change the following:
private books: BookInterface = {};
to:
private books: BookInterface[] = [];
I am making wallpaper app using ionic 3 with capacitor, I want to download and share function in my app which performs the share/download images.
My images are fetched from json data,
Please someone help me with that. Below is my code which I have checked.
I write the code to fetch the Pixabay site images using API, I want the Image Share Function.
This project is Build Ionic with Capcitor which give us the Native app.
Provider:
import { Http } from '#angular/http';
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
#Injectable()
export class ImgProvider {
key: string = 'API-KEY';
//search: string = 'quotes';
url = 'https://pixabay.com/api/?key=';
constructor(public http: Http) { }
public getimages(query:any){
return this.http.get(this.url + this.key+ "&q=" +query+ "&image_type=photo")
.map(res => res.json());
}
}
Contact.ts code:
import { Component } from '#angular/core';
import { NavController, LoadingController, ActionSheetController } from 'ionic-angular';
import { ImageViewerController } from 'ionic-img-viewer';
import { Http } from '#angular/http';
import { ImgProvider } from '../../providers/img/img';
import 'rxjs/add/operator/map';
import { SocialSharing } from '#ionic-native/social-sharing';
import { FileTransfer, FileTransferObject } from '#ionic-native/file-transfer';
import { Platform } from 'ionic-angular/platform/platform';
import { File } from '#ionic-native/file';
declare var cordova: any;
#Component({
selector: 'page-contact',
templateUrl: 'contact.html',
providers: [ImgProvider]
})
export class ContactPage {
posts = {};
search = {
params: 'nature'
};
_imageViewerCtrl: ImageViewerController;
constructor(
public navCtrl: NavController,
private transfer: FileTransfer,
imageViewerCtrl: ImageViewerController,
public http: Http,
private file: File,
public platform : Platform,
private socialSharing: SocialSharing,
public Provider: ImgProvider,
private actionSheetController: ActionSheetController,
public loadingController:LoadingController) {
this.Provider.getimages;
}
ionViewDidLoad(){
let postsLoadingController = this.loadingController.create({
content: "getting your images from server"
});
postsLoadingController.present();
this.Provider.getimages(this.search.params)
.subscribe((data) => {
postsLoadingController.dismiss();
this.posts = data
});
}
presentImage(myImage) {
const imageViewer = this._imageViewerCtrl.create(myImage);
imageViewer.present();
setTimeout(() => imageViewer.dismiss(), 1000);
imageViewer.onDidDismiss(() => alert('Viewer dismissed'));
}
doRefresh(refresher) {
this.Provider.getimages; // calls the getimages method
setTimeout(() => {
refresher.complete(); // stops the refresher 2 seconds after retrieving the data
}, 2000);
}
compileimg(index):string{
var img = this.posts[index].image ;
return img.concat(" \n sent from my awesome app");
}
regularShare(index){
var img = this.compileimg(index);
this.socialSharing.share(null, null, img, null);
}
whatsappShare(index){
var img = this.compileimg(index);
this.socialSharing.shareViaWhatsApp(null, img, null);
}
shareVia(post){
let shareViaActionSheet = this.actionSheetController.create({
title:"Share Image",
buttons:[
{
text:"Share",
icon:"share",
handler:()=> {
this.socialSharing.share(post.type,"", post.image, post.pageURL)
}
},
{
text:"Cancel",
role:"destructive"
}
]
});
shareViaActionSheet.present();
}
swipe(event) {
if(event.direction === 4) {
this.navCtrl.parent.select(1);
}
}
}
I got upload.service and 2 different modules with some components.
upload.service , upload.ts is imported to components->
Upload.module (
upload.component (everything works fine (i can upload and get photo
url data from database)
)
Ui.module )
upload.component (same function but I can't see photo , no url)
)
Working component (upload.component) :
import { Component, OnInit } from '#angular/core';
import { UploadService } from '../shared/upload.service';
import { Upload } from '../shared/upload';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'uploads-list',
templateUrl: './uploads-list.component.html',
styleUrls: ['./uploads-list.component.scss'],
})
export class UploadsListComponent implements OnInit {
uploads: Observable<Upload[]>;
showSpinner = true;
constructor(private upSvc: UploadService) { }
ngOnInit() {
this.uploads = this.upSvc.getUploads();
this.uploads.subscribe(() => this.showSpinner = false);
}
}
Not working component ( ui.component 0 errors) :
import {Component, OnInit} from '#angular/core';
import { UploadService } from "../../uploads/shared/upload.service";
import { Upload } from "../../uploads/shared/upload";
import { Observable } from "rxjs/Observable";
#Component({
selector: 'top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.scss'],
})
export class TopNavComponent implements OnInit {
uploads: Observable<Upload[]>;
show = false;
showSpinner = true;
toggleCollapse() {
this.show = !this.show;
}
constructor(private upSvc: UploadService) { }
ngOnInit() {
this.uploads = this.upSvc.getUploads();
console.log("paimama upload :", this.uploads)
this.uploads.subscribe(() => this.showSpinner = false);
}
}
I think the main problem is that I am trying to use these functions and variables from one service in two different modules - components. How to retrieve it so it would work ?
Edit (the function I am calling) :
getUploads() {
this.uploads = this.db.list(`${this.auth.userId}`).snapshotChanges().map((actions) => {
return actions.map((a) => {
const data = a.payload.val();
const $key = a.payload.key;
return { $key, ...data };
});
});
return this.uploads;
}
Html (working one in upload.component) :
<h3>File Uploads</h3>
<div *ngFor="let upload of uploads | async">
<upload-detail [upload]='upload'></upload-detail>
<img src="{{upload.url}}" alt="">
</div>
<loading-spinner *ngIf="showSpinner"></loading-spinner>
<hr>
<upload-form></upload-form>
HTML (not working ui.component)
<div *ngFor="let upload of uploads | async">
<img src="{{upload.url}}" alt="">
</div>
or
It seems that you are re-initializing your service observable each time the getUploads() method is called. This causes each component to be subscribing to a different observable, so they will not be in sync.
Don't do this if you want all components to subscribe to the same stream.
Change this:
getUploads() {
this.uploads = this.db.list(`${this.auth.userId}`).snapshotChanges().map((actions) => {
return actions.map((a) => {
const data = a.payload.val();
const $key = a.payload.key;
return { $key, ...data };
});
});
return this.uploads;
}
To this:
getUploads() {
if (!this.uploads) {
this.uploads = this.db.list(`${this.auth.userId}`).snapshotChanges().map((actions) => {
return actions.map((a) => {
const data = a.payload.val();
const $key = a.payload.key;
return { $key, ...data };
});
});
}
return this.uploads;
}
Now each component should get the same exact observable stream.
Let me know if that doesn't help.
Update:
Another approach you can take is to create a custom subject and use that as an observable. Subscribe to that observable in both components, and when you get uploads from the db you can add the upload to the stream. Each component will get the upload you add to that stream.
#Injectable()
export class UploadService {
uploadSubject: ReplaySubject<Upload> = new ReplaySubject();
upload$: Observable<Upload> = this.uploadSubject.asObservable();
getUploads() {
this.http.get(url).subscribe((upload: Upload) => {
this.uploadSubject.next(upload);
});
}
}
Now in any component, you can just subscribe to upload$ and any time the getUploads() is called, every single component subscribing to upload$ will get the value.
export class Component1 {
upload: Upload;
constructor(private uploadService: UploadService) {
uploadService.upload$.subscribe((upload: Upload) => this.upload = upload);
}
}
export class Component2 {
upload: Upload;
constructor(private uploadService: UploadService) {
uploadService.upload$.subscribe((upload: Upload) => this.upload = upload);
}
}
With this approach, just make sure to call getUploads somewhere, because the components are not calling it; they are just listening for the value it will broadcast.
Update 2:
Now I am modifying your code to work with my example above. Since this is using your code, it may not work because I may be missing certain things you have in your environment. But the original "Update" above works 100%, so use that as a guideline to get your code working. Just read the code and make sure you understand what it does and you will see that it will work for what you're doing.
UploadService:
#Injectable()
export class UploadService {
uploadStream: ReplaySubject<Upload[]> = new ReplaySubject();
uploads$: Observable<Upload[]> = this.uploadStream.asObservable();
constructor() {
this.getUploads();
}
getUploads() {
this.db.list(`${this.auth.userId}`)
.map((actions: Action[]) => {
return actions.map((action: Action) => {
const data = action.payload.val();
const $key = action.payload.key;
return new Upload({ $key, ...data });
});
})
.subscribe((uploads: Upload[]) => {
this.uploadStream.next(uploads);
});
}
}
UploadsListComponent:
import { Component } from '#angular/core';
import { UploadService } from '../shared/upload.service';
#Component({
selector: 'uploads-list',
templateUrl: './uploads-list.component.html',
styleUrls: ['./uploads-list.component.scss'],
})
export class UploadsListComponent {
constructor(public uploadService: UploadService) {}
}
UploadListComponent template:
<h3>File Uploads</h3>
<div *ngFor="let upload of uploadService.uploads$ | async">
<upload-detail [upload]='upload'></upload-detail>
<img src="{{upload.url}}" alt="">
</div>
<loading-spinner *ngIf="showSpinner"></loading-spinner>
<hr>
<upload-form></upload-form>
Now you can take the same component approach as above on your second component.
I've been stuck here since yesterday.
I have an API that retrieves data from mongodb (mlab.com)
var helpers = require('../config/helper.js');
var UserModel = require('../model/UserModel.js');
module.exports = function (server){
server.get("/", function (req, res, next) {
UserModel.find({}, function (err, users) {
helpers.success(res, next, users);
});
});
}
This is the UserModel.js
const mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var UserSchema = new Schema({
id: ObjectId,
fname: String,
lname: String,
email_add: String,
champ_type: String
});
var UserModel = mongoose.model('users', UserSchema);
module.exports = UserModel;
My app.js
//packages
const restify = require('restify');
const mongoose = require('mongoose');
const restifyValidator = require('restify-validator');
const corsMiddleWare = require('restify-cors-middleware');
//local
var setupController = require('./controller/setupController.js');
var userController = require('./controller/userController.js');
var config = require('./config/dbConfig.js');
//init packages
const server = restify.createServer();
mongoose.connect(config.getMongoConnection());
setupController(server, restify, restifyValidator, corsMiddleWare);
userController(server);
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
ALL OF THE ABOVE IS WORKING WHEN I TRIED IT ON POSTMAN
SCREENSHOT OF THE POSTMAN
NOW LET'S GO TO MY ANGULAR 5 PROJECT
First, I generate a component(retrieve.component) using the CLI.
Second, I created a service[logging.service.ts], code:
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { Injectable } from '#angular/core';// If you need external data
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '#angular/http';// If you need to call some API from the cloud
import { Request } from "#angular/http";
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { LogModel } from '../model/log.model';
#Injectable()
export class LoggingService {
private ROOT_URL = "http://localhost:8080/";
constructor(private http: Http) {}
//getPosts() {
//let params = new HttpParams().set('userId', '1');
//this.posts = this.http.get(this.ROOT_URL /*, { params }*/);
//}
addComments(): Observable<LogModel[]> {
let headers = new Headers({ "Content-Type": "application/json" }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http
.get(this.ROOT_URL, options)
.map((response: Response) => response.json())
.catch((error: any) =>Observable.throw(error.json().error || "Server error"));
}
test() {
//console.log("Hello!");
const subject = new Subject();
subject.subscribe({
next: function(value) {
console.log(value);
}
});
subject.next("Hello!");
subject.next("Free!");
}
}
Third, I created a model (log.model.ts), code:
export interface LogModel {
lname: String;
fname: String;
email_add: String;
champ_type: String;
}
Fourth, I configured my component (retrieve.component.ts), code:
import { Component, OnInit } from '#angular/core';
import { Observable } from "rxjs/Observable";
import { LoggingService } from "../service/logging.service";
import { LogModel } from "../model/log.model";
#Component({
selector: "app-retrieve",
templateUrl: "./retrieve.component.html",
styleUrls: ["./retrieve.component.css"]
})
export class RetrieveComponent implements OnInit {
//posts: Observable<any>;
private results: LogModel[];
private model: any;
constructor(private _loggingservice: LoggingService) {}
getAllusers() {
this.model = this._loggingservice.addComments().subscribe(data => {
this.results = data;
//this.results = Array.of(this.results);
}
err => console.error(err),
() => console.log('getBooks completed')
);
console.log(this.model);
}
ngOnInit() {
this._loggingservice.test();
}
}
Fifth, configured my retrieve.component.html, code:
<p>
retrieve works!
</p>
<button (click)="getAllusers()">Get Posts</button>
<div *ngFor="let item of results?.data">
<p>Output: {{ item }}</p>
</div>
Sixth, configured my app.module.ts, code:
// This typescript file is called a module. It is a group of components bundled together.
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {
NgForm,
FormBuilder,
FormGroup,
Validators,
FormArray,
FormControl,
FormsModule
} from "#angular/forms"; // for you to enable ngModel in HTMLs
//import { HttpClientModule } from '#angular/common/http';
import { HttpModule } from "#angular/http";
import { AppComponent } from './app.component';
// Before you can use a component, you'll need to declare it here
import { ServerComponent } from './server/server.component';
import { ServersComponent } from './servers/servers.component';
import { ProfileComponent } from './iprofile/profile.component';
import { ProfileService } from './iprofile/profile.service';
import { LoggingService } from './service/logging.service';
import { RetrieveComponent } from './retrieve/retrieve.component';
#NgModule({
declarations: [
AppComponent,
// Then here.
ServerComponent,
ServersComponent,
ProfileComponent,
RetrieveComponent
],
imports: [
BrowserModule,
FormsModule, // for you to enable ngModel in HTMLs
HttpModule
],
providers: [ProfileService, LoggingService],
bootstrap: [AppComponent]
})
export class AppModule {}
Lastly, I implement it on the main html (app.component.html), code:
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Welcome to {{ name }}!
</h1>
<img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<input type="text" [(ngModel)]="name">
<h3>Facker</h3>
<hr>
<app-servers></app-servers>
<app-profile></app-profile>
<app-retrieve></app-retrieve>
<!--
<h2>Here are some links to help you start: </h2>
<ul>
<li>
<h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
</li>
</ul> -->
Here's the screenshot of the output PS. When I press "get Posts" button it shows "[Object object]"
So, thank you for reading all the stuff. I just want to know what goes wrong? I just want to display to my Angular 5 project what the postman displayed. I'm trying to google simple tutorials but it doesn't work. By the way, restify and corsmiddleware are my default packages, what I mean is you can suggest but I think that won't solve the problem.
So, you have got this piece of code:
getAllusers() {
this.model = this._loggingservice.addComments().subscribe(data => {
this.results = data;
//this.results = Array.of(this.results);
data here is represented as a json, but you want it to be an object. Try to JSON.parse() your data like this:
getAllusers() {
this.model = this._loggingservice.addComments().subscribe(data => {
this.results = JSON.parse(data);
If this isn't working, try to JSON.stringify() your response instead of response.json here:
return this.http
.get(this.ROOT_URL, options)
.map((response: Response) => response.json())
Here I give working example of getting response from API and parsing it into custom object:
public loadPage() {
this.http
.get(environment.API_URL + "search/" + this.query + "/" + pageToLoad.toString())
.map((data) => JSON.stringify(data))
.subscribe((data) => {
const page: Product[] = JSON.parse(data);
this.showedProducts = this.showedProducts.concat(page);
});
}