I am getting an error while trying to read a json. I am using asp.net web api.
My code looks like this:
export class ProdutoListaPage {
public produto: Array<string>;
private url: string = "http://localhost:50907/api/consulta/BuscaProduto";
constructor(public navCtrl: NavController, public navParams: NavParams, public http:Http) {
this.http.get(this.url).map(res => res.json())
.subscribe(data => {
this.produto = data.data.children;
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad ProdutoListaPage');
}
}
If your api response is this : the correct way to assign the produto array is this : this.produto = data;
Related
What I tried to do:
private readonly IConfiguration _config;
public LoginController(IConfiguration config)
{
_config = config;
}
private static JwtSecurityToken GetToken(List<Claim> authClaims)
{
var key = _config["Jwt:Key"];
... Another code
}
I get this error:
enter image description here
appsettings.json:
"Jwt": {
"Key": "WTAuthenticationHIGHsecuredPasswordVVVp1OH7Xzyr",
"Issuer": "Issuer",
"Audience": "Audience"
},
error message is too clear:
An object reference is required for the nonstatic field, method, or
property 'member'
you should send IConfiguration as parameter to static method.
private static JwtSecurityToken GetToken(List<Claim> authClaims, IConfiguration config)
{
var key = config["Jwt:Key"];
}
while using:
public IActionResult Get(){
var claims = GetClaims();
var token = GetToken(claims, _ config)
}
I have service that extends EntityCollectionServiceBase of ngrx\data
#Injectable()
export class ProductService extends EntityCollectionServiceBase<Product> {
constructor(elementsFactory: EntityCollectionServiceElementsFactory) {
super('Product', elementsFactory);
}
and my asp.net controller is like this
[Route("api/[controller]")]
[ApiController]
public class ProductController : ApiController
{
// GET: api/<ProductController>
[HttpGet]
public async Task<ActionResult<ProductsListVm>> GetAll()
{
var vm = await Mediator.Send(new GetProductsListQuery());
return Ok(vm);
}
// GET api/<ProductController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
}
so when I call GetAll on entity service of ngrx\data it requests {url}/api/products/ while the asp.net web API controller only responds to {url}/api/product/
any configuration or trick to resolve with minimal code
You should define a plural name as follwoing:
import { EntityMetadataMap } from 'ngrx-data';
const entityMetadata: EntityMetadataMap = {
Product: {},
};
const pluralNames = { Product: 'product' };
export const entityConfig = {
entityMetadata,
pluralNames
};
I'm using Angular CLI and Spring Boot.
Everything works (getEmployee, deleteEmployee) but when I want to Update or Create (same method, and same HTML Form) an Employee I get in HTML Console/Network this error:
[ERROR] message: "Request method 'PUT' not supported"
This is my Controller:
#RestController
#RequestMapping("/api")
public class EmployeeController {
private final EmployeeServiceImpl employeeService;
#Autowired
public EmployeeController(EmployeeServiceImpl employeeService) {
this.employeeService = employeeService;
}
#GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeService.findAllEmployees();
}
#GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(#PathVariable(value = "id") Long employeeId) {
Employee employee = employeeService.findById(employeeId).get();
return ResponseEntity.ok().body(employee);
}
#PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(#PathVariable(value = "id") Long employeeId,
#Valid #RequestBody Employee employeeDetails) {
Employee employee = employeeService.findById(employeeId).get();
employee.setEmailAddress(employeeDetails.getEmailAddress());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
employee.setStatus(employeeDetails.getStatus());
employee.setSkills(employeeDetails.getSkills());
final Employee updatedEmployee = employeeService.saveEmployee(employee);
return ResponseEntity.ok(updatedEmployee);
}
#DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(#PathVariable(value = "id") Long employeeId) {
Employee employee = employeeService.findById(employeeId).get();
employeeService.deleteEmployee(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}//close class
This is also my CORSConfig:
#Configuration
public class CORSConfiguration implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedHeaders("*")
.allowedMethods("GET", "POST", "DELETE","PUT");
}
}//close class
Here you can see my Angular code:
EmployeeDetail.ts
export class EmployeeDetailsComponent implements OnInit {
#Input()
employee: Employee;
skills;
constructor(
private route: ActivatedRoute, /* holds information about the route to this instance of the EmployeeDetailsComponent */
private location: Location,
private employeeService: EmployeeService,
private skillService: SkillService
) {
}
ngOnInit() {
this.getEmployee();
this.skillService.getSkills().subscribe(res => this.skills = res);
}
getEmployee(): void {
const id = +this.route.snapshot.paramMap.get('id');
if (id === -1) {
this.employee = new Employee();
} else {
this.employeeService.getEmployee(id)
.subscribe(employee => this.employee = employee);
}
}
save(): void {
this.employeeService.updateEmployee(this.employee)
.subscribe(() => this.goBack());
console.log('test', this.employee);
}
goBack(): void {
this.location.back();
}
}
When I click on save the method redirect me to the Update method in my service;
service.ts
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
#Injectable({
providedIn: 'root'
})
export class EmployeeService {
private baseUrl = 'http://localhost:8080/api/employees';
constructor(private http: HttpClient) { }
/** GET Employees from the server */
getEmployees(): Observable<Employee[]> {
return this.http.get<Employee[]>(this.baseUrl);
}
getEmployee(id: number): Observable<Employee> {
const url = this.baseUrl + '/' + id;
return this.http.get<Employee>(url);
}
/** PUT: update the employee on the server */
updateEmployee(employee: Employee): Observable<any> {
return this.http.put(this.baseUrl, employee, httpOptions);
}
deleteEmployee(id: number): Observable<any> {
return this.http.delete(`${this.baseUrl}/${id}`, { responseType: 'text' });
}
}
This is my first SpringBoot app, also w/Angular so I never seen this error before.
What can I do?
Your Angular code shows the following method
updateEmployee(employee: Employee): Observable<any> {
return this.http.put(this.baseUrl, employee, httpOptions);
}
You did not include id in angular side. But for your spring boot side requires id. Since you are not passing the id the framework cannot find matching method resulting in 405 method not allowed error
#PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(#PathVariable(value = "id") Long employeeId,
#Valid #RequestBody Employee employeeDetails) {
Employee employee = employeeService.findById(employeeId).get();
employee.setEmailAddress(employeeDetails.getEmailAddress());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
employee.setStatus(employeeDetails.getStatus());
employee.setSkills(employeeDetails.getSkills());
final Employee updatedEmployee = employeeService.saveEmployee(employee);
return ResponseEntity.ok(updatedEmployee);
}
Hi I have this controller method that returns a list of customers and displays it using a model.
#Controller
public class timesheetController
{
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/getCustomers")
public String getCustomers(Model view)
{
//get customers from dao
List<Customer> results = customerDAO.getCustomers();
//add the customers to the model
view.addAttribute("customers", results);
return "list-customers";
}
}
However I would like to return the list as a json to get an output like
{
"Customer_Code": T77A,
"Customer_Name": CustomerName1
},
{
"Customer_Code": T77B,
"Customer_Name": CustomerName2
}
I tried just returning the list as follows
#Controller
public class timesheetController
{
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/getCustomers")
public List<Customer> getCustomers()
{
//get customers from dao
List<Customer> results = customerDAO.getCustomers();
return results;
}
}
but then I get this error as it seems to be expecting a view. How can I return the desired json output?
well you are trying to call getCustomers.jsp. What you want, instead, is not a JSP page but a JSON response. So you should make an AJAX call (by using JQuery or other framework or native JS)
So what I would do is change your Controller class in this way:
#Controller
public class timesheetController
{
#Autowired
private CustomerDAO customerDAO;
#GetMapping("/getCustomers", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE })
public ResponseEntity<List<Customer>> getCustomers()
{
List<Customer> payload = customerDAO.getCustomers();
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(payload);
}
}
Then I would make the JSON call (I'm using JQuery in this example):
var baseUrl = YOUR_WEB_APP_CONTEXT/getCustomers;
$.ajax({
type: "GET",
url: baseUrl,
success: function(data) {
//All OK.. you should have the JSON response
},
error: function() {
//Something was wrong; you chould check
}
});
I tried to integrate vue.js with Spring Boot. This is my vue.js code:
<template>
// ...
</template>
<script>
export default {
name: "Login",
data: function() {
return {
username: '',
password: '',
msg: ''
}
},
methods: {
// post data to Spring Boot
login() {
axios.post('/login',{
username: this.username,
password: this.password
})
.then(function(response) {
if(response.data.code === 200){
this.$store.dispatch('setCurrentUser',this.username);
// vue-route
this.$router.push('/course');
} else {
this.msg = response.message;
}
})
.catch(function(err) {
this.msg = 'error';
});
}
}
};
</script>
And this is my Spring Boot controller:
#RestController
#ResponseBody
public class LoginController {
#Autowired
private ResultGenerator resultGenerator;
#PostMapping("/login")
public RestResult login(String username, String password){
if(username.equals("123") && password.equals("123")){
return resultGenerator.getSuccessResult();
} else {
return resultGenerator.getFailResult("error");
}
}
}
The controller will return JSON data which looks like:{"code":200,"message":"success","data":null}. When the login method was called, controller could accept the username and password and controller sent response data too. But that was all and vue-router didn't work. All I saw in the brower was:
Can anyone help?
------------------ Addition -----------------------
This is vue-router config:
const routes = [
{
path: '/',
component: Login
},
{
path: '/signin',
component: Signin
},
{
path: '/course',
component: Course
}
];
const router = new VueRouter({
routes,
mode: "history"
});
The problem could be that you return resultGenerator.getSuccessResult(). Have you tried redirecting to the '/course' path inside Spring Boot Controller?
#PostMapping("/login")
public RestResult login(String username, String password){
if(username.equals("123") && password.equals("123")){
this.$router.push('/course');
} else {
return resultGenerator.getFailResult("error");
}
}
If the Vue.js and Spring boot are 2 different apps (like backend and frontend), this may help:
Try using #CrossOrigin (CORS) on your #controller or on the method that expose the rest, I had similar issues on an Ionic 3 proyect and thaty solved the problem.
EXAMPLE:
#CrossOrigin(origins = "http://localhost:9000")
#GetMapping("/greeting")
public Greeting greeting(#RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
It should look something like this:
#RestController
#ResponseBody
public class LoginController {
#Autowired
private ResultGenerator resultGenerator;
#CrossOrigin(origins = "http://localhost:9000") // The IP:PORT of the vue app origin
#PostMapping("/login")
public RestResult login(String username, String password){
if(username.equals("123") && password.equals("123")){
return resultGenerator.getSuccessResult();
} else {
return resultGenerator.getFailResult("error");
}
}
}
Source from spring.io Here! :D