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);
});
}
Related
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)
There are many examples around the web on this subject but none of them helped me. This is the scenario: I've got 2 components and a service. The two components aren't parent/children but are 2 independent components. One of them has a list of names, the other should load a table when one of the names is clicked. This is my home.html with both components
<div class="material-docs-app">
<div class="docs-primary-header">
<h1>Yep!</h1>
</div>
<div fxLayout="row" fxLayout.xs="column" class="component-layout-body">
<app-heroes-sidenav></app-heroes-sidenav>
<app-heroes-table #heroesTable fxFlex="1 2 calc(15em + 20px)" style="width: 100%"></app-heroes-table>
</div>
</div>
Heroes sidenav component:
<div *ngIf="loadingData == true">
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div>
<nav *ngIf="loadingData == false">
<p *ngFor="let item of heroesNames.results let i = index" [attr.data-index]="i">
<button mat-button (click)="getHero(i)">
{{item.name}}
</button>
</p>
</nav>
On click getHero() is called correctly. This is the sidenav component ts:
import { Component, OnInit, Input } from '#angular/core';
import {SwCharactersServiceService} from '../sw-characters-service.service';
import {HeroesTableComponent} from '../heroes-table/heroes-table.component';
#Component({
selector: 'app-heroes-sidenav',
templateUrl: './heroes-sidenav.component.html',
styleUrls: ['./heroes-sidenav.component.css']
})
export class HeroesSidenavComponent implements OnInit {
heroesNames: any;
heroData:any;
loadingData = true;
#Input() heroesTable: HeroesTableComponent;
constructor(private _swService: SwCharactersServiceService) { }
ngOnInit() {
this.getHeroes();
}
getHeroes() {
this._swService.getCharacters().then(result => {
this.loadingData = false;
this.heroesNames = result;
});
}
getHero(index) {
this._swService.getHero(index);
}
}
and this is the service:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import 'rxjs/add/operator/map'
import {Observable} from 'rxjs/Observable';
#Injectable({
providedIn: 'root'
})
export class SwCharactersServiceService {
param:any;
constructor(private http: HttpClient) { }
getCharacters(): Promise<any[]> {
return this.http.get<any[]>("https://swapi.co/api/people/")
.toPromise()
.then(result => result)
.catch(this.handleError);
}
getHero(index): Observable<any>{
console.log(index);
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.get("https://swapi.co/api/people/" + index, {
headers: headers
}).map(res => res );
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
I can correctly see the console.log(index) but the request doesn't work. There is no request initiated in chrome console network tab.
This is the component with the table:
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import { Subscription } from 'rxjs/Subscription';
import {SwCharactersServiceService} from '../sw-characters-service.service';
#Component({
selector: 'app-heroes-table',
templateUrl: './heroes-table.component.html',
styleUrls: ['./heroes-table.component.css']
})
export class HeroesTableComponent implements OnInit {
loadingData = true;
heroData :any;
subscription: Subscription;
constructor(private _swService: SwCharactersServiceService) {
this.subscription = this._swService.getHero(1).subscribe(result => { this.heroData = result; });
console.log(this.heroData);
}
ngOnInit() {
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
There are 2 problems now:
1) As you can see I wrote this._swService.getHero(1) without passing a dynamic param. How does it work? How can I pass the correct index?
2) The service doesn't fire and I haven't got any result.
Is there any other way to do that?
Thanks.
you can use BehaviourSubject to pass the index value and send the query request as the list is cliked
in the service
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
public index: BehaviorSubject<number> = new BehaviorSubject<number>(null);
in the sidenav component
getHero(index) {
this._swService.index.next(index);
}
in the hero table component
ngAfterViewInit(){
this._swService.index.subscribe(index=>{
if(index){
this._swService.getHero(index).subscribe(result => { this.heroData = result; });
}
})
}
You missed to subscribe to _swService.getHero(). If not subscribed to a method which returns an Observable, then it wont be invoked.
getHero(index) {
this._swService.getHero(index).subscribe(
(resp) => {
// manipulate your response here
console.log(resp);
},
(err) => {}
);
}
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'm learning angularjs2. Here Ihave tried to call API and got response. But the response not render in homepage.component.html. I'm not sure what Im wrong. and I want use this response in another page also without calling API again. I dont know how to that. Please help with this.
homepage.component.ts
import { Component, OnInit,Injectable } from '#angular/core';
import {Http, Response} from '#angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from 'rxjs/Rx';
import { Router } from '#angular/router';
import { CountriesService } from './countries.services';
import { Countries } from './countries';
#Component({
moduleId: module.id,
selector: 'my-homepage',
templateUrl: 'homepage.component.html',
styleUrls: [ 'homepage.component.css' ],
providers: [ CountriesService ]
})
export class HomepageComponent implements OnInit {
errorMessage: string;
public edited = false;
Countries : Countries[];
constructor(private router: Router,private CountriesService: CountriesService) { }
ngOnInit(){
this.CountriesService.getCountries().subscribe(
Countries => {Countries = Countries,console.log(Countries);},
error => this.errorMessage = <any>error);
}
}
homepage.component.html
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 remove_padding images">{{Countries.msg}} Test
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 remove_padding" *ngFor="let Cities of Countries">
<img class="img-responsive" src="{{Cities.img}}" alt="{{Cities.city}}">
<div class="topleft">
{{Cities.city}}
<p class="city_para">{{Cities.country}}</p>
<!--<p>23 food places and more!</p>-->
</div>
</div>
</div>
countries.services.ts
import { Injectable } from '#angular/core';
import { Http, Headers,Response} from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Countries } from './countries';
#Injectable()
export class CountriesService {
private CountryListUrl = "APIURL";
private CityByCatUrl = "APIURL";
constructor(private http: Http) {}
getCountries(): Observable<any> {
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,OPTIONS');
headers.append('Access-Control-Allow-Origin', '*');
return this.http.get(this.CountryListUrl,{headers: headers})
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let Countries = res.json();
console.log(Countries);
return Countries || { };
}
private handleError(error: Response) {
return Observable.throw(error.json().error || "500 internal server error");
}
}
countries.ts
export class Countries {
Status: Number;
msg: String;
categorylist:JSON ;
}
You need to see what you are actually receiving:
{
"Status":1,
"categorylist":[
{
// whatever properties you have...
"id":1,
"city":"cityOne"
}
// more...
],
"msg":"List Found!"
}
Countries is not an array that you can iterate, it's an object, with an array inside it, called categoryList. I suppose that is what you want to iterate through.
So when you have subscribed to your object, and notice the subscribe, you need to assign the data to your Object Countries:
.subscribe(data => {
this.Countries= data;
});
And as said, Countries is not an array, but an object, so you should change the initialization from Countries : Countries[]; to Countries:Countries = {}
You can iterate the categoryList that is inside the object:
<div *ngFor="let Cities of Countries.categorylist">
<a>{{Cities.city}}</a>
</div>
Not really knowing what your array contains, you need to adjust the properties accordingly in your own code.
Here's a
DEMO
PS. No need to use a class here, change your Countries to Interface and change categorylist: JSON to....
export interface Countries {
Status: Number;
msg: String;
categorylist: array[];
}
The problem is with your data population. Can you check adding this.Countries while assigning the response.
ngOnInit(){
this.CountriesService.getCountries().subscribe(
Countries => {
Countries = this.Countries,
console.log(Countries);
},
error => this.errorMessage = <any>error);
}
EDIT: Comment by OP:
"Sorry , but I think I had had slight typo in enviroment/environment, sorry for wasting your time ,it seems to work now"
I have having trouble passing data from app components to child component in angular 2 . I recently started toying with angular 2 and trying to understand how it works. I tried to used the concept shown in this tutorial to do pass data to child component
https://angular.io/docs/ts/latest/tutorial/toh-pt3.html
But I think I am missing something
Here is my project: App component:
import { Component, ViewChild } from '#angular/core';
import { WorkflowService } from './components/workflow_display/workflow.service';
import { WorkflowDisplayComponent } from './components/workflow_display/workflow-display.component';
import { PropertyService } from './shared/property.service';
import '../../public/css/styles.css';
#Component({
selector: 'my-app',
template: require('./app.component.html')
})
export class AppComponent {
title = 'Hello World';
#ViewChild("taskDisplay") workflowDisplay: WorkflowDisplayComponent;
myEnvironment: String; //the variable I am trying to bind from
errorMessage: String;
workbenchBaseUrl : String = 'workbenchBaseUrl';
public selectedNavID : String = 'workspace_control_workStreamView';
public isWorkOrdersCollapsed = false;
public isWorkStreamsCollapsed = false;
constructor(private _propertyService : PropertyService){
}
ngOnInit(): void {
this._propertyService.getValue(this.workbenchBaseUrl)
.subscribe(environment => this.myEnvironment = environment,
error => this.errorMessage = <any>error);
}
}
app.component.html
<div>
<div>
<div>
<!--some html-->
<main class="col-sm-9 offset-sm-3 col-md-10 offset-md-2 pt-3 mh-100">
<workflow-display [environment] ="myEnvironment" #taskDisplay></workflow-display>
</main>
</div>
</div>
</div>
WorkDisplay component
import { Component, Input} from '#angular/core';
import { OnInit } from '#angular/core';
import { IGrcTask } from './grc-task';
import { WorkflowService } from './workflow.service';
import { PropertyService } from '../../shared/property.service';
#Component({
selector: 'workflow-display',
template: require('./workflow-display.component.html')
})
export class WorkflowDisplayComponent implements OnInit {
taskMode: string = 'workstream'; // 'workorder' or 'workstream' to currently identify the columns to display
taskQuery: string = 'process=workstream&taskStatus=RUNNING'; // the query parameters to pass to the tasks web service
workbenchUrl: string = 'http://localhost:8081'; // workbench URL
workbenchTaskPage: string = 'wsIndex'; // workbench page to use to open tasks
infoMessage: string;
errorMessage: string;
tasks: IGrcTask[];
currentTask: IGrcTask;
#Input()
environment: String; //the variable I am trying to bind to
workbenchBaseUrl : String = 'workbenchBaseUrl';
constructor() {
}
//called when user clicks a row
openTask(event: any, task: any) {
// this.environment is still undefined
window.open(this.environment + this.workbenchTaskPage + "?taskId=" + task.taskId + "&activitiWorkflow=true");
}
}
WorkDisplay.component.html
<--!some html-->
<tbody *ngIf='(taskMode == "workorder") && tasks && tasks.length'>
<ng-container *ngFor='let task of tasks; let i=index'>
<tr (click)="setCurrentTask($event, task)" (dblclick)="openTask($event, task)"
<--!some html-->
Property.service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
/**
* Service return Property value/values from the project property file
*
*/
#Injectable()
export class PropertyService {
//ReST Url for the PopertyService on the back end
private _url = '/grcworkflow/resources/grcWorkflow/environment/';
constructor(private _http: Http) {}
/**
* Method return an Observable<String -> Value> for any property
* Method make an http get call to the server to fetch the property
* #Param key for the property in the property file
*/
getValue(key: String): Observable<String> {
return this._http.get(this._url+key)
.map((response: Response) => <String> response.text())
.do(data => console.log('All: ' + data))
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.json().error || 'Server error');
}
}
NOTE I have removed some function definitions and variable from the components which might be irrelevant.
I am trying to bind myEnviroment value of the app.component enviroment value. myEnviroment get set when proerty service returns a string. Although enviroment value still stays undefined .
I am looking for one way binding i.e when myEnvironment(parent) changes environment(child) should change too. But this doesn't seem to happen. Please help out here