How to retrieve certain data from URL in Angular 2.0 - javascript

I have a URL like this one:
https://example.com/?username1=Dr&Organization=Pepper&action=create
I need to display it on my browser inside a text box.
<input type="text" name="varname" value="Dr">
I need to get Dr in my textbox

I'm presuming your url endpoint returns JSON and your attempting to use the returned data to populate your input value.
Firstly import the HttpClientModule in your module dependencies:
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Then from within your foo.component.ts you can inject an instance of HttpClient in the constructor.
constructor(private http: HttpClient){
}
Then you can use said HttpClient instance http like so:
this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
console.log(data);
});
}
This can then be put into a property (myProp) which can be referenced like so:
<input *ngIf="myProp" type="text" name="varname" value="myProp">
Note that we use *ngIF to make sure that our property isn't loaded until myProp is not null or undefined.
Main App component - app-root
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
name = null;
constructor(private http: HttpClient){
}
ngOnInit(): void {
this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
// data = result: {name: 'Derek da Doctor'}
this.name = data.result.name;
});
}
}
app.component.html
<input *ngIf="name" type="text" name="varname" value="{{name}}">

Related

How can I set text of button in angular reactive form

I have a form which allows me to create a new record or update an existing one. Right now the text of the button is submit. Based on if I call the form with an optional parameter which in my case is the id of the record to edit I set my form mode as create or update. What I want is to be able to set the text displayed as either create or update but I have not found a way to change the text from my controller. I can set all field values and enable or disable the submit button but have not found a way to set the Text on button. Can this be done and if not is there a work around
In your ts file.
export class AppComponent {
buttontext="Create"
name = 'Angular';
}
In your HTML File
<button>{{buttontext}}</button>
You can change button text accordingly.In your functions
See here-https://stackblitz.com/edit/angular-wsxkz9
If you are looking for some other solution you have to create your own directive
CustomDirective.ts file
import { Directive, ElementRef, Input, Renderer2 } from '#angular/core';
#Directive({ selector: '[myHidden]' })
export class HiddenDirective {
constructor(public el: ElementRef,private renderer: Renderer2) {}
#Input() myHidden: boolean;
ngOnInit(){
// Use renderer to render the emelemt with styles
console.log(this.myHidden)
if(this.myHidden) {
this.renderer.setProperty(this.el.nativeElement, 'innerHTML', 'Create');
}
else{
this.renderer.setProperty(this.el.nativeElement, 'innerHTML', 'Delete');
}
}
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HiddenDirective } from './customdirective';
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent,HiddenDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
val="true";
name = 'Angular';
}
app.component.html
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<button [myHidden]="val"></button>
See this- https://stackblitz.com/edit/angular-ktf7e3

Angular 7 shared service is not shared

I am new to angular and I am trying to pass data from one component(HomeComponent) to another component(ProfileComponent) after navigation.
I created a shared service(DataService).
I injected the service in both the HomeComponent and ProfileComponent but when I set the value of the message property in HomeComponent and try to retrieve it in the ProfileComponent the value is undefined because the DataService is not the same instance.
The DataService was registered in the AppModule in the providers array so it should be a shared service and always the same instance right?
Thanks in advance
DataService.ts
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class DataService {
message:string;
constructor() { }
}
HomeComponent.ts
import { Component, OnInit } from '#angular/core';
import { DataService } from '../services/data/data.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private data:DataService) { }
ngOnInit() {
this.data.message = "hello world";
}
}
ProfileComponent.ts
import { Component, OnInit } from '#angular/core';
import { DataService } from '../services/data/data.service';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
private message : string;//undefined
constructor(private data:DataService) { }
ngOnInit() {
this.message = this.data.message;
}
}
AppModule.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DataService } from './services/data/data.service';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
ProfileComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
I know it's a 2 year question, but Google puts it at the top of search results
Now, Angular docs are clearer about this (or just we can find out easier), it's called "Singleton Services"
The section that explains this "bug" is The ForRoot Pattern and it says:
"If a module defines both providers and declarations (components, directives, pipes), then loading the module in multiple feature modules would duplicate the registration of the service. This could result in multiple service instances and the service would no longer behave as a singleton."
To sum up, if you define this in your services (DataService.ts) the providedIn: root as follows
#Injectable({ providedIn: 'root' })
you need to avoid define the service as a provider on your components or modules.
AppModule.ts
...
imports: [
BrowserModule,
AppRoutingModule
],
providers: [DataService], // This line is the problem
bootstrap: [AppComponent]
....
Hope that helps to somebody and if need more documentation refer to Singleton Services' link
Each time you inject the service to your component, new instance is generated. However in this case i would recommend you to use BehaviorSubject as follows,
#Injectable()
export class SharedService {
private messageSource = new BehaviorSubject<string>("default message");
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
STACKBLITZ DEMO

angular 4 : Can't bind to 'ngForFor' since it isn't a known property of 'li'

I've just started learning angular 4. This is a simple code that I'm trying to implement in Visual Studio Code, but keep getting this error.
Uncaught Error: Template parse errors:
Can't bind to 'ngForFor' since it isn't a known property of 'li'. ("
</ul>
<ul>
<li [ERROR ->]*ngFor="let hobby for hobbies">{{hobby}}</li>
</ul>"): ng:///AppModule/UserComponent.html#6:6
Property binding ngForFor not used by any directive on an embedded template.
Make sure that the property name is spelled correctly and all directives are
listed in the "#NgModule.declarations".("
</ul>
<ul>
[ERROR ->]<li *ngFor="let hobby for hobbies">{{hobby}}</li>
</ul>"): ng:///AppModule/UserComponent.html#6:2
I tried previous solutions of adding the CommonModule to the app.module file. But it hasn't solved the issue.I cannot figure out what is wrong.
app.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { UserComponent } from './components/user/user.component';
import {CommonModule} from '#angular/common';
#NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule,CommonModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
user.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
name:string;
age:number;
address: Address;
hobbies:string[];
constructor() {
console.log('constructor ran ...');
}
ngOnInit() {
console.log('ngOnInit ran ...');
this.name='Raul';
this.age=22;
this.address= {
street:'abc',
city:'xyz',
country: 'jkl'
}
this.hobbies=['reading','playing','swimming'];
}
}
interface Address{
street:string,
city:string,
country:string
}
user.component.html:
<h1>{{name}}</h1>
<ul>
<li>Age:{{age}}</li>
<li>Address:{{address.street}}, {{address.city}},{{address.country}}</li>
</ul>
<ul>
<li *ngFor="let hobby for hobbies">{{hobby}}</li>
</ul>
should be of instead of for inside the ngFor
ngFor="let hobby of hobbies"

Angular HttpClientModule errors

I am working on my first Angular app and dealing with the HttpClientModule in my component and getting errors.
following the docs Angular -HttpClient I installed the HttpClientModule in the app.module.ts as instructed, then in my emails.component.ts I have the following:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-emails',
templateUrl: './emails.component.html',
styleUrls: ['./emails.component.scss'],
results: string[]
})
export class EmailsComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get('/api/email_list.json').subscribe(data => {
this.results = data['results'];
});
}
}
which is giving me the following error in my console:
ERROR in src/app/components/emails/emails.component.ts(7,3): error TS2345: Argument of type '{ selector: string; templateUrl: string; styleUrls: string[]; results: any; }' is not assignable to parameter of type 'Component'.
Object literal may only specify known properties, and 'results' does not exist in type 'Component'.
src/app/components/emails/emails.component.ts(7,12): error TS2693: 'string' only refers to a type, but is being used as a value here.
src/app/components/emails/emails.component.ts(7,19): error TS1109: Expression expected.
src/app/components/emails/emails.component.ts(12,29): error TS2304: Cannot find name 'HttpClient'.
src/app/components/emails/emails.component.ts(16,12): error TS2339: Property 'results' does not exist on type 'EmailsComponent'.
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { EmailsComponent } from './components/emails/emails.component';
#NgModule({
declarations: [
AppComponent,
EmailsComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
you're component should be:
first you need to import HttpClient
second results: string[] should be inside the class not at decoration component exactly as I did here :
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-emails',
templateUrl: './emails.component.html',
styleUrls: ['./emails.component.scss']
})
export class EmailsComponent implements OnInit {
results: string[];
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get('/api/email_list.json').subscribe(data => {
this.results = data['results'];
});
}
}
Please read the description carefully, they explaining you need to load HttpClient.
In your app module you forgot to provide.
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { AppComponent } from './app.component';
import { EmailsComponent } from './components/emails/emails.component';
#NgModule({
declarations: [
AppComponent,
EmailsComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [HttpClient],
bootstrap: [AppComponent]
})
export class AppModule { }
Then in your component:
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-emails',
templateUrl: './emails.component.html',
styleUrls: ['./emails.component.scss']
})
export class EmailsComponent implements OnInit {
results: string[]
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get('/api/email_list.json').subscribe(data => {
this.results = data['results'];
});
}
}

shared service is unable to pass data to next component

I have created two components and one shared service, i want pass data from one component to another, but i am getting empty object
bellow is 1st component
import { Component, OnInit } from '#angular/core';
import {SharedService} from './../shared.service';
import { Router, NavigationStart } from '#angular/router';
#Component({
selector: 'app-cone',
templateUrl: './cone.component.html',
styleUrls: ['./cone.component.css'],
providers: [SharedService]
})
export class ConeComponent implements OnInit {
req = <any>{};
constructor(public service:SharedService,private router:Router) { }
send(){
this.req.fname= "ketan";
this.req.lname= "pradhan";
this.service.saveData(this.req);
console.log('str');
this.router.navigate(['/apps/ctwo']);
}
ngOnInit() {
}
}
Bellow is the 2nd component where i need to pass the data from 1st comonent, i am getting empty object is this.myName
import { Component, OnInit } from '#angular/core';
import {SharedService} from './../shared.service';
import { Router, NavigationStart } from '#angular/router';
#Component({
selector: 'app-ctwo',
templateUrl: './ctwo.component.html',
styleUrls: ['./ctwo.component.css'],
providers: [SharedService]
})
export class CtwoComponent implements OnInit {
myName= <any>{};
constructor(public service:SharedService,private router:Router) {
this.myName=this.service.getData();
console.log(this.myName);
}
ngOnInit() {
}
}
Bellow is shared service which is for communicating between 2 components
import {Component, Injectable,Input,Output,EventEmitter} from '#angular/core'
// Name Service
export interface myData {
name:string,
lname:string
}
#Injectable()
export class SharedService {
sharingData: myData=<any>{};
saveData(str){
console.log('save data function called' + str.fname);
console.log(this.sharingData);
this.sharingData = str;
// this.sharingData.lname=str.lname;
console.log(this.sharingData)
}
getData()
{
console.log('get data function called');
return this.sharingData;
}
}
When you are setting providers arrays at component level, it means that you have two separate instances of the service in this case.
You need to declare the service in your NgModule providers array instead, then the two components (and any other components in that module) will have the same instance of the service.
So remove the providers arrays in your components, and instead add the service to providers array in your NgModule.
#Component({
selector: 'app-ctwo',
templateUrl: './ctwo.component.html',
styleUrls: ['./ctwo.component.css'],
// providers: [SharedService] // remove these!
})
and instead....
#NgModule({
imports: [ ... ],
declarations: [ .. ],
bootstrap: [ ... ],
providers: [ SharedService ] // here!
})

Categories