如何为angular 6中的所有组件使用公共类url?
我有一个公共类,该公共类在所有组件中导入,该公共类url在所有组件中使用,但该公共url不起作用,因此如何在angular中为所有组件创建公共url(因为将来我必须仅在公共类中为commonUrl进行更改) category.component.html如何为angular 6中的所有组件使用公共类url?,angular,Angular,我有一个公共类,该公共类在所有组件中导入,该公共类url在所有组件中使用,但该公共url不起作用,因此如何在angular中为所有组件创建公共url(因为将来我必须仅在公共类中为commonUrl进行更改) category.component.html <button mat-button><img src="commonUrl/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/><
<button mat-button><img src="commonUrl/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/></button>
<td mat-cell *matCellDef="let element">
<img src="commonUrl/{{element.userimage}}" style="height: 40px;width: 40px;"/>
</td>
follow.component.html
<button mat-button><img src="commonUrl/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/></button>
<td mat-cell *matCellDef="let element">
<img src="commonUrl/{{element.userimage}}" style="height: 40px;width: 40px;"/>
</td>
最好创建一个静态变量来访问公共url
export class CommonClass {
public static commonUrl : string = 'http://localhost:3000'
}
在category.component.ts中访问该属性
categoryimage = CommonClass.commonUrl
<button mat-button><img src="commonUrl/{{categoryimage}}" style="height: 100px;width: 100px;"/></button>
categoryimage=CommonClass.commonUrl
在app.module.ts
文件中为url添加提供程序。您的代码应该如下所示
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
...........
],
providers: [
........
//use this line
{ provide: 'API_URL', useValue: 'http://localhost:3000' },
]
})
在你的组件中,你必须注入它
export class YourComponent {
apiUrl: string;
constructor(@Inject('API_URL') apiUrl: string) {
this.apiUrl = apiUrl;
}
}
现在,您可以在组件中的任何位置使用该url,首先需要在组件中导入类,然后在视图中创建该类的实例 这里有一个例子 在
.ts中
import {CommonClass} from ../yourfolder/commomurl
commonClassObj: CommonClass = new CommonClass();
在.html
<button mat-button><img src="{{commonClassObj.commonUrl}}/{{categoryObj.categoryimage}}" style="height: 100px;width: 100px;"/></button>
如果不起作用,另一种方法是:使用输出来发出值
@Output() commonUrl : EventEmitter<Boolean> = new EventEmitter<Boolean>();
并在要使用此通用URL的组件中使用@Input()
希望它有帮助最好的方法是使用文件夹
environnements
中的文件
在文件environnement.dev.ts
中:
export const environment = {
production: false,
apiUrl: 'http://localhost:3000',
};
使用环境变量:
import { environment } from '../../environments/environment';
在您的组件中:
apiUrl = environment.apiUrl;