【问题标题】:How to get attribute in angular side after sending a response from server side (servlet)从服务器端(servlet)发送响应后如何在角度端获取属性
【发布时间】:2021-01-28 14:57:18
【问题描述】:
@WebServlet("/findPerson")
public class FindPerson extends HttpServlet {
    // ... doGet implementation

    @Override
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException {

        // data to send to the client
        String name = "John White";
        int age = 54;



        // Adding attributes to the request
        request.setAttribute( "personName", name );
        request.setAttribute( "personAge", age );

        }
    }
}

调用后如何以角度获取这些属性“personName”和“personAge”的值

return  this.http.post('http://localhost:8080/findPerson',"");

【问题讨论】:

    标签: angular http servlets request


    【解决方案1】:

    this.http.post() 返回一个 observable。您需要订阅它才能获得响应

    服务

    findPerson(): Observable<any> {
      return this.http.post('http://localhost:8080/findPerson',"");
    }
    

    组件

    name: any;
    age: any;
    
    this.someService.findPerson().subscribe(
      res => {
        this.name = res['personName'];
        this.age = res['personAge'];
        console.log(this.name); // <-- correct
        console.log(this.age); // <-- correct
      },
      error => {
        // always good practice to handle HTTP errors
      }
    
      console.log(this.name); // <-- wrong - would print `undefined`
      console.log(this.age); // <-- wrong - would print `undefined`
    );
    

    最需要注意的是调用是异步的。因此,任何直接依赖于响应的语句应该在订阅中。或者换句话说,您需要在需要响应的地方订阅。

    您可以了解更多关于异步数据here

    【讨论】:

    • [Error] 错误 – TypeError:null 不是对象(评估 'res['status']')— login.component.ts:55 TypeError:null 不是对象(评估 'res ['status']') — login.component.ts:55(匿名函数) — login.component.ts:55__tryOrUnsub — ....
    • @Ashim:看来服务器没有发回任何东西。我不熟悉 HttpServlet,但我没有看到返回的内容。例如。我没有看到响应的 MIME 类型。请查看here,了解如何从 Servlet 返回 JSON 格式的对象。
    猜你喜欢
    • 2020-03-04
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 2012-02-21
    相关资源
    最近更新 更多