Able to receive response from server as a JSON object.Tried to cast JSON object to emp (type Employee),but not happening. What is the problem with my code?? Is there another way to solve this??
app.component.ts
export class AppComponent implements OnInit{
title = 'httpClientProject';
posts : JsonGet[];
emp : Employee;
constructor(private appService : AppService,private employeeService : EmployeeService){}
ngOnInit(){
this.getData();
this.getEmployee();
console.log(this.emp) }
getData() : void{
this.appService.getData().subscribe(posts=>(this.posts = posts)); }
getEmployee() : void{
this.employeeService.getEmployee().subscribe(data=>this.emp={...data}); } }
employee.service.ts
export class EmployeeService {
private baseUrl = 'http://localhost:8080/SpringRestWebService/getSingleEmployye';
constructor(private http: HttpClient) { }
getEmployee(): Observable<Employee> {
return this.http.get<Employee>(this.baseUrl); } }
Employee.ts
export class Employee {
public id: number;
public name: string;
public city: string;
constructor(id:number, name:string, status:string) {
this.id = id;
this.name = name;
this.city = status; } }
Json Response From Server
{
"id": 1,
"name": "asdasd",
"city": "Hasdasdayd"
}
Just define type when passing variable in subscribe
getEmployee() : void{
this.employeeService.getEmployee().subscribe((data:Employee)=>{
this.emp=data;
}
}
Related
I was wondering how can I use string value of JSON object that I get from input.
export class NavComponent implements OnInit {
formVar: FormGroup;
items = [];
constructor(private api: ApiService, private fb: FormBuilder) {}
ngOnInit(): void {
this.formVar = this.fb.group({
search:''
});
}
onSubmit(){
this.api.search(this.formVar.value).subscribe(
data => {
this.items = data;
console.log(this.formVar.value);
}
)
}
}
The output for fromVar.value is this:
{search: "dfsdf"}
search: "dfsdf"
__proto__: Object
but I need only string value inside this object.
I figured it out:
this.formVar.controls['search'].value
instead of:
this.formVar.value
I try to map a Json http request answer to an object array (User) using RxJs :
My Json data looks like :
{"#context":"\/cotabe\/api\/contexts\/User","#id":"\/cotabe\/api\/users","#type":"hydra:Collection","hydra:member":[{"#id":"\/cotabe\/api\/users\/1","#type":"User","id":1,"email":"a.a#gmail.com","firstname":"Aaa","lastname":"Ggg","phone":"0606060606","mobile":"0606060607","fullName":"Aaa Ggg","username":"a.a#gmail.com","roles":["ROLE_DEVROOT","ROLE_USER"],"password":"$argon2i","createdAt":"-0001-11-30T00:00:00+01:00","updatedAt":"-0001-11-30T00:00:00+01:00","deleted":false}],"hydra:totalItems":1}
I would like to extract from that a User[], with user model :
export class User {
constructor(
public id: number,
public email: string,
public firstname: string,
public lastname: string,
public phone: string,
public mobile: string,
public roles: string[],
) {}
}
In my user service I have :
export class UserService {
private users: User[] = [];
userSubject = new Subject<User[]>();
constructor(private apiService: ApiService) { }
emitUsers() {
this.userSubject.next(this.users.slice());
}
getUsersFromRest() {
this.apiService.getEntriesFromRest('users').subscribe(
(data: User[])=>{
this.users = data['hydra:member'];
});
this.emitUsers();
}
}
with in an api service
public getEntriesFromRest (option: string): any {
return this.httpClient.get<any[]>(this.baseEndpoint + option);
}
I know it is an rXjs operator stuff, but I did not manage to find the solution.
Thank you for your help,
export class UserService {
userSubject = new Subject<User[]>();
userSubject$ = this.userSubject.asObservable();
constructor(private apiService: ApiService) {}
getUsersFromRest() {
this.apiService
.getEntriesFromRest("users")
.pipe(
map(x => JSON.stringify(x)),
map(x => JSON.parse(x)),
pluck("hydra:member")
)
.subscribe((data: User[]) => {
this.usersSubject.next(data);
});
}
}
Can you try the above code
export class UserService {
private userSubject = new Subject<User[]>();
userSubject$ = this.userSubject.asObservable(); // If you add a public observable of your subject, you can have other components subscribe to this, and not be able to alter the subject, but still get the data.
constructor(private apiService: ApiService) { }
getUsersFromRest() {
this.apiService.getEntriesFromRest('users')
.pipe(
map((x: any) => JSON.parse(x)) // Convert your response from JSON to an Object
.subscribe(
(data: User[]) => {
this.usersSubject.next(data.hydra.member);
});
}
}
There is no need to have a separate emit users method.
I am using jhipster, which uses Angular and spring boot
I have been working on this contact form that requests the user to input their information and send it. The email is sent without problems but when the email comes to the inbox the subject, name, and body text all say "null". I have tried many different options like postmapping and method.post, but it still returns the same null value.
Please help, this is the only item not working in my project
Here is my SmtpMailSender
#Component
public class SmtpMailSender {
private JavaMailSender javaMailSender;
#Autowired
public SmtpMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void sendNotification(UserModel usermodel) throws MailException{
StringBuilder sb = new StringBuilder();
sb.append("Name: " +
usermodel.getName()).append(System.lineSeparator());
sb.append("\n Message: " + usermodel.getMessage());
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo(usermodel.getEmail());
mail.setFrom("emailremoved#gmail.com");
mail.setSubject(usermodel.getSubject());
mail.setText(sb.toString());
javaMailSender.send(mail);
}
}
and my rootcontroller that will send the code
#RestController
public class RootController {
#Autowired
private SmtpMailSender smtpMailSender;
#RequestMapping("/api/contact")
public String signupSuccess(#RequestParam(value="subject",required=false)
String subject, #RequestParam(value="message",required=false) String
message, #RequestParam(value="email",required=false) String email,
#RequestParam(value="name",required=false) String name) {
UserModel usermodel = new UserModel();
usermodel.setSubject(subject);
usermodel.setMessage(message);
usermodel.setEmail("emailremoved#gmail.com");
usermodel.setName(name);
try {
smtpMailSender.sendNotification(usermodel);
}catch(MailException e) {
}
return "redirect:/home.component.html";
}
}
And my typescriptcode
#Component({
selector: 'jhi-contact',
templateUrl: './contact.component.html',
styles: ['input.ng-invalid{border-left:5px solid red;}input.ng-valid{border-
left: 5px solid green;}'],
providers: [NgbModalConfig, NgbModal]
})
export class ContactComponent implements OnInit {
model: UserModel = {
name: '',
email: '',
subject: '',
message: ''
};
constructor(private http: HttpClient, private router: Router, config:
NgbModalConfig, private modalService: NgbModal) {
config.backdrop = 'static';
config.keyboard = false;
}
open(content) {
this.modalService.open(content);
}
ngOnInit() {}
sendNotification(): void {
const url = 'http://localhost:9000/api/contact';
this.http.post(url, this.model).subscribe(res => {
location.reload();
});
this.router.navigate(['']);
}
}
export interface UserModel {
name: string;
email: string;
subject: string;
message: string;
}
I'm new in Angular.
I've a class called User:
export class User {
private id: number;
private name: string;
private surname: string;
get Id(): number {
return this.id;
}
set Id(newId: number) {
this.id = newId;
}
get Name(): string {
return this.name;
}
set Name(newName: string) {
this.name = newName;
}
get Surname(): string {
return this.surname;
}
set Surname(newSurname: string) {
this.surname = newSurname;
}
}
...a function to retrive an array of user:
getValues() {
this.usersService.getUsers()
.subscribe((users: User[]) => this.dataSource = users);
}
and a method to retrive the users array from backend WebApi:
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.usersSearchUrl)
.pipe(
tap(users => this.log(`fetched users`)),
catchError(this.handleError('getUsers', []))
);
}
finally the json returned from the webapi:
[{"id":"1","name":"Alberico","surname":"Gauss"},{"id":"2","name":"Anassimandro","surname":"Dirac"},{"id":"3","name":"Antongiulio","surname":"Poisson"}]
I would have expected that the call would automatically mapped the User class, instead it only gives me an array of type User, in fact if I write something in my component .subscribe((utenti: Utente[]) => console.log(utenti[0].Surname)); the console writes me "undefined". Can you tell me where I'm wrong? Thanks
You are retrieving JSON from your backend, as is expected. A Javascript (or typescript) class is not the same thing.
When the JSON is returned, it can be automatically converted into a simple JSON object in Javascript but it will NOT include all your getters and setters. So these class methods are not available, which is why you get undefined.
Remove all the getters and setters and add a constructor. Then you can just call Surname directly as a property and it will return the value (since it will then just be a plain JSON object).
export class User {
constructor() {
}
public id: number;
public name: string;
public surname: string;
}
Or without a constructor, and just declare the properties directly:
export class User {
public id: number;
public name: string;
public surname: string;
}
Or you could also use an interface:
export interface User {
id: number;
name: string;
surname: string;
}
You can read more about this issue here and here.
I think in component ts use like this code:
users: User[];
constructor(
private us: usersService,
public auths: AuthService
)
this.us.getUsers.subscribe(
users=> {
this.users= users.map((user) => {
return new User(user);
});
}
);
In service I think to write:
public getUsers(): Observable<User[]> {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.getUsers), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(user=> {
return new User(user);
});
}
});
}
For me this logic work perfect. I hope to help you with this code
I'm having problems deserializing a .NET List into an Angular 2 array. I keep receiving an error:
ERROR Error: Cannot find a differ supporting object...NgFor only supports binding to Iterables such as Arrays.
I've checked here but none of the proposed solutions have been working for me: https://github.com/angular/angular/issues/6392
C#
Model
public class Filter
{
public string filterType { get; set; }
public string filterKey { get; set; }
public string filterValue { get; set; }
}
Controller Action
public List<Filter> Filters { get; set; } = new List<Filter>()
{
new Filter()
{
filterType = "TypeA",
filterValue = "ValueA",
filterKey = "TypeA|ValueA"
},
new Filter()
{
filterType = "TypeB",
filterValue = "ValueB",
filterKey = "TypeB|ValueB"
}
};
// GET api/values
[HttpGet]
public ActionResult Get()
{
var response = JsonConvert.SerializeObject(Filters);
return new JsonResult(response);
}
I have confirmed with both POSTMAN and Chrome Developer Tool's that this controller is correctly returning the JSON:
[{"filterType":"TypeA","filterValue":"TypeA","filterKey":"TypeA|ValueA"},
{"filterType":"TypeB","filterValue":"ValueB","filterKey":"TypeB|ValueB"}]
Angular
Model (filter.ts)
export class Filter{
filterType: string;
filterKey: string;
filterValue:string;
}
Service (filter.service.ts)
#Injectable()
export class FilterService {
private apiUrl: string = "http://localhost:7639/api/filters";
constructor(private http: Http) { }
public getFilters = (): Observable<Filter[]> => {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.apiUrl,options)
.map(res => <Filter[]>res.json())
.do(x => console.log(x)) <-- This clearly logs the JSON
.catch(this.handleError);
}
private handleError(error:Response){
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
Component (filter.component.ts)
export class FilterComponent implements OnInit{
title = 'Filters';
public filters: Filter[];
constructor(private filterService: FilterService) {
}
ngOnInit() {
this.getFilters();
}
private getFilters(){
this.filterService.getFilters().subscribe(filters => {
this.filters = filters;
console.log(filters);
},
error => {
console.log(error);
}, () => {
});
}
}
Component HTML (filter.component.html)
<h1>{{title}}</h1>
<div *ngFor="let filter of filters">
<p>{{filter.filterType}}</p>
<p>{{filter.filterValue}}</p>
<p>{{filter.filterKey}}</p>
</div>
Any help with this would be appreciated
The answer was super simple.
// GET api/values
[HttpGet]
public ActionResult Get()
{
var response = JsonConvert.SerializeObject(Filters);
return new JsonResult(response);
}
I was doing redundant serialization on the list and passing the response back as a string.
Changing the above method corrected the issue:
// GET api/values
[HttpGet]
public ActionResult Get() => new JsonResult(Filters);