javascript - 如何从 Angular 2.0 中的 URL 检索某些数据

标签 javascript angular

我有一个像这样的 URL:

https://example.com/?username1=Dr&Organization=Pepper&action=create

我需要在我的浏览器上的一个文本框中显示它。

<input type="text" name="varname" value="Dr">

我需要在我的文本框中获取 Dr

最佳答案

我假设您的 url 端点返回 JSON 并且您尝试使用返回的数据来填充您的输入值。

首先在您的模块依赖项中导入 HttpClientModule:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

然后在您的 foo.component.ts 中,您可以在构造函数中注入(inject)一个 HttpClient 实例。

constructor(private http: HttpClient){
  }

然后你可以像这样使用HttpClient实例http:

this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
      console.log(data);
    });
  }

然后可以将其放入属性 (myProp) 中,可以像这样引用它:

<input *ngIf="myProp" type="text" name="varname" value="myProp">

请注意,我们使用 *ngIF 来确保在 myProp 不是 nullundefined 之前不会加载我们的属性


主要的 App 组件 - app-root

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 = 'app';
  name = null;


  constructor(private http: HttpClient){
  }

  ngOnInit(): void {
    this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
    // data = result: {name: 'Derek da Doctor'}
      this.name = data.result.name;
    });
  }
}

app.component.html

<input *ngIf="name" type="text" name="varname" value="{{name}}">

关于javascript - 如何从 Angular 2.0 中的 URL 检索某些数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48348848/

相关文章:

<mat-list-option> 复选框的 Angular Material Change 主题颜色

javascript - 如何让 Google Contact API 与 AngularJS 一起工作?

javascript - 向上遍历并找到属性等于特定值的子元素

模板驱动表单的 Angular 条件验证

javascript - 无法使用 Renderer2 更改使用 ViewChild 引用的按钮的属性

Angular 为什么我们需要 markForCheck 当 detectChanges 也有效时

javascript - 带有点、空格和数字的正则表达式 javascript

javascript - 单击复选框+按钮后动态更改 slider 值

javascript - for 循环不进行条件检查

forms - 防止 Angular 2 在编辑输入字段时应用更改