我有一个像这样的 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
不是 null
或 undefined 之前不会加载我们的属性
。
主要的 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/