How to solve the error of inside setUser()? - html

import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class BackendService {
constructor() { }
setUser(formData) {
let fackresponce3 = {
" errorCode " : "1",
"errorMessage" : "User Created",
"rowCount" : "30",
"data" :{
"token" : "abcd"
}
};
let fackresponce1 = {
" errorCode " : "0",
"errorMessage" : "Some Error",
"rowCount" : "30",
"data" :{
"token" : "abcd"
}
};
return Observable.create(
observer => {
setTimeout ( () => {
observer.next( fackresponce3)
}
,2000)
});
}
}

You can use the of operator to create a new observable. Then pipe that observable and use the delay operator instead of the setTimeout.
https://www.learnrxjs.io/operators/creation/of.html
https://www.learnrxjs.io/operators/utility/delay.html
// backend.service.ts
import { of, delay, Observable } from 'rxjs';
export interface IResponse{
data: string;
}
#Injectable({
providedIn: 'root'
})
export class BackendService {
constructor() { }
setUser(formData?:any): Observable<IResponse> {
const fakeData = {} as IResponse;
return of(fakeData).pipe(delay(2000));
}
}
// note observables do not fire until they are subscribed to... so you can use it as follows
// app.component.ts
import { Component, Subscription, OnInit, OnDestroy } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private backendService: BackendService){}
ngOnInit(){
this.subscription = this.backendService
.setUser()
.subscribe(data => console.log(data));
}
ngOnDestroy(){
// also note to unsubscribe OnDestroy otherwise you will end up with a memory leak
this.subscription.unsubscribe();
}
}
// app.module.ts
#NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
providers: [ BackendService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Related

Why does the function run twice in my every component

I have this problem where i made three different components with routing. The problem is when i open my different components they loop twice at the moment i open them. What is causing this and how can i get rid of it?
Heres one example component which console.log runs twice when i open it.
import { Component, OnInit } from '#angular/core';
import nameData from '../../names/names.json'
interface INames {
name: string,
amount: number
}
const { names } = nameData
#Component({
selector: 'app-four',
templateUrl: './four.html',
styleUrls: ["./four.css"]
})
export class FourComponent {
nameArray: Array<INames> = names
constructor() {
}
hasName(nameParam: any) {
console.log("miksi tämä tulee kaksi kertaa")
return this.nameArray.some(elem => elem.name === nameParam)
}
}
And here is the app.module.ts and app-routing.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OneComponent } from './requirements/one/one';
import { TwoComponent } from './requirements/two/two';
import { ThreeComponent } from './requirements/three/three';
import { FourComponent } from './requirements/four/four';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { HeaderComponent } from './header/header';
#NgModule({
declarations: [
AppComponent,
OneComponent,
TwoComponent,
ThreeComponent,
FourComponent,
HeaderComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing-module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './home/home';
import { FourComponent } from './requirements/four/four';
import { OneComponent } from './requirements/one/one';
import { ThreeComponent } from './requirements/three/three';
import { TwoComponent } from './requirements/two/two';
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'one', component: OneComponent },
{ path: 'two', component: TwoComponent },
{ path: 'three', component: ThreeComponent },
{ path: 'four', component: FourComponent }
]
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
I'm really confused why it loops the function as soon as i press the components button?
I do not recommand at all to use function in the HTML template, because they will be called everytime the Angular's change detection runs. Angular isn't able to tell if the result of the function will be different after each modification, si Angular will call the function everytime something change in the UI.
You must store the result of the function in a variable. Angular can check that the reference of the variable hasn't change.
You can read more information about it on this medium.
I recommend that you do the following
public fullName: string;
constructor() {
this.updateName();
}
private updateName(nameParam: any) {
console.log("miksi tämä tulee kaksi kertaa");
this.fullName = this.nameArray.some(elem => elem.name === nameParam);
}
{{ fullName }}

Uncaught ReferenceError: Cannot access 'MaterialModule' before initialization

I am working on a simple form for a personal project and try to put a phone form use this example: https://material.angular,.io/components/form-field/examples and after that fits everything it gives me this error and although Remove everything related to the phone form remains the same.
form.component.ts
import { Component, OnInit } from '#angular/core';
import { Builder } from 'protractor';
import {FocusMonitor} from '#angular/cdk/a11y';
import {coerceBooleanProperty} from '#angular/cdk/coercion';
import {ElementRef, Input, OnDestroy, Optional, Self} from '#angular/core';
import {FormBuilder, FormGroup, ControlValueAccessor, NgControl} from '#angular/forms';
import {MatFormFieldControl} from '#angular/material';
import {Subject} from 'rxjs';
#Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss'],
providers: [{provide: MatFormFieldControl, useExisting: MyTelInput}],
host: {
'[class.example-floating]': 'shouldLabelFloat',
'[id]': 'id',
'[attr.aria-describedby]': 'describedBy',
}
})
export class MyTelInput implements ControlValueAccessor, MatFormFieldControl<MyTel>, OnDestroy {
static nextId = 0;
parts: FormGroup;
stateChanges = new Subject<void>();
focused = false;
errorState = false;
controlType = 'example-tel-input';
id = `example-tel-input-${MyTelInput.nextId++}`;
describedBy = '';
onChange = (_: any) => {};
onTouched = () => {};
get empty() {
const {value: {area, exchange, subscriber}} = this.parts;
return !area && !exchange && !subscriber;
}
get shouldLabelFloat() { return this.focused || !this.empty; }
#Input()
get placeholder(): string { return this._placeholder; }
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
private _placeholder: string;
#Input()
get required(): boolean { return this._required; }
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next();
}
private _required = false;
#Input()
get disabled(): boolean { return this._disabled; }
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
this._disabled ? this.parts.disable() : this.parts.enable();
this.stateChanges.next();
}
private _disabled = false;
#Input()
get value(): MyTel | null {
const {value: {area, exchange, subscriber}} = this.parts;
if (area.length === 3 && exchange.length === 3 && subscriber.length === 4) {
return new MyTel(area, exchange, subscriber);
}
return null;
}
set value(tel: MyTel | null) {
const {area, exchange, subscriber} = tel || new MyTel('', '', '');
this.parts.setValue({area, exchange, subscriber});
this.stateChanges.next();
}
constructor(
formBuilder: FormBuilder,
private _focusMonitor: FocusMonitor,
private _elementRef: ElementRef<HTMLElement>,
#Optional() #Self() public ngControl: NgControl) {
this.parts = formBuilder.group({
area: '',
exchange: '',
subscriber: '',
});
_focusMonitor.monitor(_elementRef, true).subscribe(origin => {
if (this.focused && !origin) {
this.onTouched();
}
this.focused = !!origin;
this.stateChanges.next();
});
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}
ngOnDestroy() {
this.stateChanges.complete();
this._focusMonitor.stopMonitoring(this._elementRef);
}
setDescribedByIds(ids: string[]) {
this.describedBy = ids.join(' ');
}
onContainerClick(event: MouseEvent) {
if ((event.target as Element).tagName.toLowerCase() != 'input') {
this._elementRef.nativeElement.querySelector('input')!.focus();
}
}
writeValue(tel: MyTel | null): void {
this.value = tel;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
_handleInput(): void {
this.onChange(this.parts.value);
}
}
export class MyTel {
constructor(public area: string, public exchange: string, public subscriber: string) {}
}
export class FormComponent implements OnInit {
public formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
name: '',
lastname: '',
option: '',
checkbox: '',
masculino: '',
femenino: '',
email:'',
});
}
}
form.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormRoutingModule } from './form-routing.module';
import { FormComponent } from './form/form.component';
import { MaterialModule } from '../material/material.module';
import { FormBuilder } from '#angular/forms';
#NgModule({
declarations: [FormComponent],
imports: [
CommonModule,
FormRoutingModule,
MaterialModule
],
providers: [
FormBuilder
]
})
export class FormModule { }
material.module.ts
import { NgModule } from '#angular/core';
import {
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatCheckboxModule,
MatRadioModule} from '#angular/material';
import { ReactiveFormsModule } from '#angular/forms';
import { FormModule } from '../form/form.module';
import { FormComponent } from '../form/form/form.component';
const materialModules = [
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
ReactiveFormsModule,
MatSelectModule,
MatInputModule,
MatRadioModule,
FormModule,
FormComponent,
MatCheckboxModule,
];
#NgModule({
exports: materialModules,
imports: materialModules
})
export class MaterialModule { }
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NoopAnimationsModule } from '#angular/platform-browser/animations';
import { MaterialModule } from './modules/material/material.module';
import { MatSelectModule, MatInputModule, MatCheckbox, MatRadioModule } from '#angular/material';
import { MatFormFieldModule } from '#angular/material/form-field';
import { FormModule } from './modules/form/form.module';
import { FormComponent } from './modules/form/form/form.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NoopAnimationsModule,
MaterialModule,
MatSelectModule,
MatInputModule,
MatFormFieldModule,
MatRadioModule,
FormModule,
FormComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
form-routing.component.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { FormComponent } from './form/form.component';
const routes: Routes = [{path: '', component: FormComponent}];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FormRoutingModule { }
Please help
you have 2 major errors here:
importing a component to a module. Can't be done, only modules can be imported. Components can be declared and exported. This is causing the error you're seeing.
Circular module imports by importing FormModule to MaterialModule and vice versa. Can't do it. Imports can only go in one direction. This is causing the warning you're seeing which is actually an error preventing you from recompiling.
And some minor errors, like you're mixing up module logic and double importing modules
fixes below....
material module, let it do what it's supposed to do, import and export material modules, NOTHING ELSE, remover reactive forms import, remove circular reference to FormsModule, remove form component import:
import { NgModule } from '#angular/core';
import {
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatCheckboxModule,
MatRadioModule} from '#angular/material';
const materialModules = [
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatRadioModule,
MatCheckboxModule,
];
#NgModule({
exports: materialModules,
imports: materialModules
})
export class MaterialModule { }
form module, import the reactive forms module here (dont provide the form builder), export your forms component to use it in other modules:
#NgModule({
declarations: [FormComponent],
imports: [
CommonModule, // if you have a common module, you could import / export the reactive forms module there if it's more appropriate and then you don't need to import it again here.
FormRoutingModule,
MaterialModule,
ReactiveFormsModule // do this here, don't provide the form builder
],
exports: [
FormComponent // if you want to use this component in other modules, export here and import the MODULE
]
})
export class FormModule { }
app module, don't try to import the form component, just the module. Don't reimport material modules, you do that in the material module:
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NoopAnimationsModule,
MaterialModule, // do you really NEED the material module here?
FormModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Module has no exported member 'http' [2305]

Hello I am trying to import http call from '#angular/common/http' and am getting error message that module has no exported member 'http'
Error:[ts] Module '"e:/car/node_modules/#angular/common/http"' has no exported member 'Http'. [2305]
import {
RouterModule
} from '#angular/router';
import {
BrowserModule
} from '#angular/platform-browser';
import {
NgModule
} from '#angular/core';
import {
AppRoutingModule
} from './app-routing.module';
import {
AppComponent
} from './app.component';
import {
HomeComponent
} from './home/home.component';
import {
HttpClientModule
} from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot([{
path: '',
component: HomeComponent
}])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
import {
Http
} from '#angular/common/http';
import {
Component,
OnInit
} from '#angular/core';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: Http) {}
products = [];
fetchData = function() {
this.http.get('http://localhost:5555/products').subscribe(
(res: Response) => {
this.products = res.json();
}
);
};
ngOnInit() {
this.fetchData();
}
}
the below code is used for inserting json file which includes the details
HttpClientModule will inject HttpClient service not the Http.
Please use HttpClient in constructor injection in the HomeComponent.
constructor(private http: HttpClient) {}
For Reference created sample stackblitz code.

Angular 6 component not showing up

I just started learning Angular yesterday so I apologize if I'm missing something obvious, but I am trying to display a component on the app.component.html, however, it is not showing up.
TS file for the component I am trying to display:
import { Component, OnInit } from '#angular/core';
import { ImageService } from '../shared/image.service';
#Component({
selector: 'image-list',
templateUrl: './image-list.component.html',
styleUrls: ['./image-list.component.css']
})
export class ImageListComponent implements OnInit {
images: any[];
constructor(private _imageService : ImageService ) { }
searchImages(query : string)
{
return this._imageService.getImage(query).subscribe
(
data => console.log(data),
error => console.log(error),
() => console.log("Request Completed!")
);
}
ngOnInit() {
}
}
image-list.component.html :
<button>Find Images</button>
app.component.html :
<image-list></image-list>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
image.service.ts
import { Injectable } from "#angular/core";
import { environment } from "../../environments/environment";
import { Http, Headers } from "#angular/http";
import { map, filter, scan } from 'rxjs/operators';
#Injectable()
export class ImageService
{
private query: string;
private API_KEY: string = environment.API_KEY;
private API_URL: string = environment.API_URL;
private URL: string = this.API_URL + this.API_KEY + '&q=';
constructor(private _http: Http) {
}
getImage(query)
{
return this._http.get(this.URL + this.query).pipe(
map((res) => res.json));
}
}
I had a similar problem trying to use a component outside its module.
In this case, you have to export a component from your .module.ts:
#NgModule({
// …
declarations: [ MyComponent ],
exports: [ MyComponent ],
// …
})
You need to import your Component and your Service into your app.module.ts and then to declarations and to providers property
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list.component';
import { ImageService } from './image.service';
#NgModule({
declarations: [
AppComponent,
ImageListComponent
],
imports: [
BrowserModule
],
providers: [ ImageService ],
bootstrap: [AppComponent]
})
export class AppModule { }
Adjust ImageListComponent path into the import statement.
Teorically when you generate a component with Angular CLI with a command like this:
ng generate component image-list
it should update your app.module.ts file for you.
To generate a service use
ng generate service image
check this one
in src/app/app.module.ts
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule, HttpClientModule],
bootstrap: [AppComponent],
})
export class AppModule {}
from this link: https://malcoded.com/posts/why-angular-not-works/
You may try the Angular tutorial from: https://angular.io/start . It shows how to render a custom Ansible component on the app.component.html page.
You just need to update the app.module.ts file. Assuming your component is named ImageListComponent:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router'; // add this line
import { AppComponent } from './app.component';
import { ImageListComponent } from './image-list/image-list.component'; // add this line
#NgModule({
declarations: [
AppComponent,
ImageListComponent // add this line
],
imports: [
BrowserModule,
// add the following 3 lines
RouterModule.forRoot([
{ path: '', component: ImageListComponent },
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
First try this, without adding any custom services.
It seems you have nothing that triggers the API call on your method searchImages in ImageComponent. Having a click eventListener on the <button>Find Images</button> tag should do the trick. Also register the ImageComponent and ImageService in your app.module.ts file.

Pull data from a json file and display it with a button

I am trying to pull data from a json file and display it, but I am unable to proceed with the program because I lack experience in coding Angular.
Currently using Angular 4.3, which uses HttpClientModule.
app.component.ts
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 = '?';
data;
constructor(private http: HttpClient) {
}
ngOnInit(): void {
this.http.get('/src/app/students.json')
}
chgTab1() {
this.title = "Changed Title";
}
chgTab2() {
//Want to display the items from json file
}
}
students.json
[
{"id": "3", "mame": "Dama"},
{"id": "1", "mame": "ASD"},
{"id": "2", "mame": "Chris"},
{"id": "4", "mame": "Sass"},
]
import { Component, OnInit } from '#angular/core';
import { Http,Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = '?';
data;
showData = false;
constructor(private http: Http) { }
ngOnInit(): void {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.get('/assets/students.json', { headers: headers }).map(res => res.json()).subscribe(data => {
this.data = data;
})
}
chgTab1(){
this.title ="Changed Title";
}
chgTab2(){
//Want to display the items from json file
this.showData = !this.showData;
}
}
I have edited the whole thing. It will now work for you. Ensure you have the path to your student.json in the correct place.I moved it to the assets directory