Comparing Data in Subscribe Angular & Observable RXJS - javascript

I am new to Angular & have written below code using in-memory-web-api for Login POC,
DB-service.service:
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let users = [
{id: 1, username: 'user1', password:'user1', name:'John'},
{id: 2, username: 'user2', password:'user2', name:'David'},
{id: 3, username: 'user3', password:'user3', name:'Brad'},
{id: 4, username: 'user4', password:'user4', name:'Jim'},
{id: 5, username: 'user5', password:'user5', name:'Saun'}
];
return {users};
}
}
user.service:
import { loginUser } from '../_model/user';
#Injectable()
export class UserService {
private headers = new Headers({ 'Content-Type': 'application/json' });
private userUrl = 'api/users'; // URL to web api
constructor(private http: Http) {
}
getLogin(username: string, password: string) {
const url = `${this.userUrl}`;
return this.http.get(url).map(res => res.json());
}
}
model/user.ts
export class loginUser {
constructor(
public id: number,
public username: string,
public password: string,
public name: string) { }
}
login.component.ts
login(form: FormGroup) {
if (this.loginForm.valid) {
this.userData.getLogin(form.value.loginUserTxt, form.value.loginPassTxt)
.subscribe(
data => {
console.log(data);
//comparing the data from the array in DB-service.service
},
error => {
console.log("Fail");
});
}
My issue is that how can I compare that data in subscribe of login.component.ts with the input value.

I have update the code below in subscribe
this.loggedUser = this.userData.getAuthenticate(data, form.value.loginUserTxt, form.value.loginPassTxt)
if (this.loggedUser == "Invalid") {
//error
} else {
//redirect
}
Thanks all

Related

Logged in user can see only his own content (Angular+Firebase)

I have a file named user.service.ts with a following code (I set firebase authentication here):
export class UserService {
uid = this.afAuth.authState.pipe(
map((authState) => {
if (!authState) {
return null;
} else {
return authState.uid;
}
})
);
isAdmin: Observable<boolean>= this.uid.pipe(
switchMap(uid=>{
if(!uid){
return observableOf(false);
} else{
return this.firebase.object<boolean>('/admin/'+ uid).valueChanges()
}
})
);
constructor(private afAuth: AngularFireAuth, private firebase: AngularFireDatabase) {}
login() {
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
}
logout() {
this.afAuth.auth.signOut();
}
I have a file named employee.service.ts, and this is how I insert employees in firebase:
insertEmployee(employee) {
this.employeeList.push({
caseId: employee.caseId,
caseName: employee.caseName,
department: employee.department,
startDate: employee.startDate==""?"":this.datePipe.transform(employee.startDate, 'dd.MM.yyyy'),
startTime: employee.startTime,
finishTime: employee.finishTime,
isPermanent: employee.isPermanent,
description: employee.description,
remark: employee.remark,
serviceType: employee.serviceType,
isReplaceable: employee.isReplaceable,
maintainer: employee.maintainer,
contracts: employee.contracts,
dnevnica: employee.dnevnica,
client: employee.client
});
}
In the same file, I get employees like:
getEmployees(){
this.employeeList=this.firebase.list('employees');
return this.employeeList.snapshotChanges();
}
My question is: How I can connect this insert with client id? To be more concrete, I want to make every user see only his content, how can I do that?

Mongoose strict mode true is not working for nested object

I have this Schema
const TransportSchema = new mongoose.Schema({
id: {
type: String,
require: true,
unique: true,
index: true
},
driver: {
_id: mongoose.Schema.Types.ObjectId,
username: String,
registrationId: String,
name: String
}
})
When I update the document using "updateOne" and a driver object like this:
import { v4 as uuidv4 } from 'uuid';
export default class User {
public readonly id: String;
public registrationId: String;
public name: String;
public username: String;
public role: String;
public passwordHash: String;
public createdAt: Date;
constructor(props: Omit<User, 'id'>, id?: String) {
Object.assign(this, props);
if(!id) {
this.id = uuidv4();
} else {
this.id = id;
}
}
}
async assignDriver(id: String, driver: User): Promise<boolean> {
const result = await MongoTransportModel.updateOne(
{ id },
{ driver, driverAssignedAt: Date.now() }
);
return !!result.nModified;
}
I don't want it to save the fields I haven't declared in the schema like "passwordHash", and it is saving. I tried to use strict: true and doesn't work.

Interface and class in Reactjs

i was having a model class: of structure:
export default class Info {
empId: number;
name: string;
designation: string
constructor(data) {
this.empId = data.empId;
this.name = data.name;
this.designation = data.designation;
}
}
I have to change this class to an interface.
export default interface Info{
empId: number;
name: string;
designation: string
}
service class:
getInfo(): Promise<Array<Info>> {
return http
.get(this.ENDPOINTS.PRODUCTS, {
})
.then((response) => {
console.log("response", response)
return response.data.map((info) => new Info(info));
)
})
.catch((error) => {
throw error;
});
}
I am getting error in this line return response.data.map((info) => new Info(info)); stating 'Info' only refers to a type, but is being used as a value here. Can anyone help me with how to deal with the interface here and what will be the syntax. Can please anyone help me in understanding when to use Class and Interface in React app

Json server: Error: Insert failed, duplicate id

Hii all I am trying to post data to json server using post method , but unfortunately I have erros, my app have buttons follow, likes etc , I want when user clicks follow numbers increase and saved to the json file , so now when user clicks button I get the following error :
Note: am using fakes json server : Fake Json server
Error: Insert failed, duplicate id
at Function.insert (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\lodash-id\src\index.js:49:18)
at C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\lodash\lodash.js:4374:28
at arrayReduce (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\lodash\lodash.js:683:21)
at baseWrapperValue (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\lodash\lodash.js:4373:14)
at LodashWrapper.wrapperValue (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\lodash\lodash.js:9052:14)
at create (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\lib\server\router\plural.js:221:52)
at Layer.handle [as handle_request] (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\router\route.js:137:13)
at next (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\router\route.js:131:14)
at Route.dispatch (C:\Users\jelly\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\router\route.js:112:3)
POST /statuses 500 13.873 ms - -
Here is service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import {Status } from '../model/statuses.model';
import { Comment } from '../model/comments.model';
#Injectable({
providedIn: 'root'
})
export class UserService {
status: Status[];
constructor(private http: HttpClient) { }
statusUrl = 'http://localhost:3000/statuses';
commentsUrl = 'http://localhost:3000/comments';
getStatuses() {
return this.http.get<Status[]>(this.statusUrl);
}
addStatus(status: Status) {
return this.http.post(this.statusUrl, status);
}
addComments(comment: Comment) {
return this.http.post(this.commentsUrl, comment);
}
}
here is ts file :
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { UserService } from '../service/user.service';
import { Status } from '../model/statuses.model';
import { Comment } from '../model/comments.model';
import {FormBuilder, FormGroup, Validators} from '#angular/forms';
#Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {
status: Status[];
comment: Comment[];
constructor(private formBuilder: FormBuilder, private http: HttpClient, private userService: UserService) { }
addForm: FormGroup;
ngOnInit() {
this.addForm = this.formBuilder.group({
id: [],
name: ['', Validators.required],
city: ['', Validators.required],
description: ['', Validators.required],
});
this.userService.getStatuses()
.subscribe( data => {
this.status = data;
console.log(data);
console.log(this.status);
});
}
addComments() {
this.userService.addComments(this.addForm.value)
.subscribe(data => {
this.comment.push(this.addForm.value);
});
}
followButtonClick(statusId) {
const statusToUpdate = this.status.filter(status => status.id === statusId)[0];
statusToUpdate.followers++;
statusToUpdate.following++;
this.persistStatus(statusToUpdate);
}
likesButtonClick(statusId) {
const statusToUpdate = this.status.filter(status => status.id === statusId)[0];
statusToUpdate.like++;
this.persistStatus(statusToUpdate);
}
persistStatus(status) {
this.userService.addStatus(status)
.subscribe(data => {
this.status = status;
});
}
}
Here is json file :
{
"statuses": [
{
"id": 1,
"statusId": 20,
"likes": 121,
"following": 723,
"followers": 4433
}
]
}
Here is model
export class Status {
id: number;
statusId: number;
like: number;
following: number;
followers: number;
}
what am I doing wrong in my code ????
From documentation of the fake json-server you are using,:
Id values are not mutable. Any id value in the body of your PUT or
PATCH request will be ignored. Only a value set in a POST request will
be respected, but only if not already taken.
You are trying to update an existing status, so you need a put call not post. Something like this:
updateStatus(status: Status) {
return this.http.put(this.statusUrl + '/' + status.id, status);
}
And use it in the persistStatus function.
persistStatus(status) {
his.userService.updateStatus(status)
.subscribe(data => {
this.status = [status];
});
}

Angular - Re-Populate form inputs from service

I have a basic angular component that allows some one to edit the details of a user once they go to their profile and click on "edit".
Component:
export class EditUserComponent implements OnInit {
// Define our vars
user: Users[];
editUserForm: FormGroup;
message: {};
displayMessage = false;
userID: number;
errorMessage: any = '';
constructor(
private fb: FormBuilder,
private _userService: UserService,
private activatedRoute: ActivatedRoute
) {
}
ngOnInit(): void {
// Get the userID from the activated route
this.activatedRoute.params.subscribe((params: Params) => {
this.userID = params['id'];
});
// Call our service and pass the UserID
this._userService.getUser(this.userID)
.then(res => {
this.user = res;
this.createForm();
});
}
// Generate the form
createForm() {
this.editUserForm = this.fb.group({
QID: ['', Validators.required],
favoriteColor: [''],
favoriteNumber: [''],
favoriteActor: ['']
});
}
}
Service:
// Fetch a single user
getUser(userID: number) {
return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers })
.toPromise()
.then(res => res.json())
.catch(err => { this.handleError(err); });
}
Interface:
export interface Users {
RecordID?: number;
QID: string;
favoriteColor?: string;
favoriteNumber?: number;
favoriteActor?: string;
}
I am trying to pass the values to my formGroup but I am having trouble figuring out how to access the values.
I assumed I could do something like this where I could access the user model and select a property from it but that is throwing an undefined error.
Would I pass the values here in the form group or bind them to the elements directly somehow? I am receiving the data back from the service just fine, just not sure how to get each of the values back to their respective fields.
createForm() {
this.editUserForm = this.fb.group({
QID: [this.user.QID, Validators.required],
favoriteColor: [''],
favoriteNumber: [''],
favoriteActor: ['']
});
}
If I understand correctly ... this is what my code looks like:
onProductRetrieved(product: IProduct): void {
if (this.productForm) {
this.productForm.reset();
}
this.product = product;
// Update the data on the form
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode,
starRating: this.product.starRating,
description: this.product.description
});
this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
}
I'm using patchValue for the values and setControl for the array.
OR
Since you are creating the form after retrieving the data, you could do something like this:
createForm() {
this.editUserForm = this.fb.group({
QID: [this.user.QID, Validators.required],
favoriteColor: [this.user.favoriteColor],
favoriteNumber: [this.user.favoriteNumber],
favoriteActor: [this.user.favoriteActor]
});
}
AND just to be complete ... each input element needs a formControlName property like this:
<input class="form-control"
id="productNameId"
type="text"
placeholder="Name (required)"
formControlName="productName" />
<span class="help-block" *ngIf="displayMessage.productName">
{{displayMessage.productName}}
</span>
</div>
You can find a complete working example here: https://github.com/DeborahK/Angular2-ReactiveForms
Bind a submit event to your form, then use this.editUserForm.value to access the data from the form.
In the component template:
<form [formGroup]="editUserForm" (submit)="saveIt()">
In the Component:
saveIt() {
if (this.editUserForm.dirty && this.editUserForm.valid) {
alert(`Number: ${this.editUserForm.value.favoriteNumber} Actor: ${this.editUserForm.value.favoriteActor}`);
}
}

Categories

Resources